【问题标题】:Set UIBarButtonItem gray color when disabled禁用时设置 UIBarButtonItem 灰色
【发布时间】:2017-05-26 18:29:33
【问题描述】:

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

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

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

我尝试阅读以下内容:

UIBarButtonItem is disabled, but has normal color

Change color of disabled bar button item in iOS

当它未被禁用时,我可以更改颜色。似乎当它被禁用时,颜色不被遵守?

【问题讨论】:

  • 我也遇到了这个错误,它似乎只发生在 Swift 或最近的 iOS 版本中。我的解决方法是使用常规 UIButton 并将 UIBarButtonItem 用作自定义视图。 UIButton可以正常修改。

标签: uibarbuttonitem


【解决方案1】:

当它被禁用时,颜色不被遵守?

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

例如在 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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多