禁用时设置 UIBarButtonItem 灰色

Set UIBarButtonItem gray color when disabled

我有一个 UIColor 扩展,可以从十六进制字符串中获取颜色。我按照以下方式使用它:

    self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(hexString: "#C0BFC0")], for: UIControlState.disabled)
    self.navigationItem.rightBarButtonItem?.isEnabled = false

出于某种奇怪的原因,rightBarButtonItem 的颜色与以前相同。有没有办法在禁用时更改它?我的 viewDidLoad 函数中有以上内容

我尝试阅读以下内容:

我可以在未禁用时更改颜色。似乎当它被禁用时颜色不符合?

when its disabled the colors are not obeyed?

我遇到了一些工具栏项目的错误。我的解决方法是确保 UIBarButtonItem 标题在运行时更改,此时禁用的颜色应该更改。为此,请更改禁用的颜色,然后在需要时通过添加不可见的 Unicode space 强制更改标题。

例如 Swift:

let zeroWidthSpaceStr = "\u{200B}"

func forceChangeItemTitle(_ item:UIBarButtonItem, newTitle:String) {
    // Ensure the button item title is changed. Needed to pick up change in disabled text color
    var newTitle = newTitle
    if item.title == newTitle {
        // Title already set, so change it invisibly
        newTitle += zeroWidthSpaceStr
    }
    item.title = newTitle
}