1

I have an extension for UIColor to get color from hex string. I'm using it as per below:

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

For some strange reason the color of the rightBarButtonItem is the same as before. Is there a way to change it when disabled? I have the above in my viewDidLoad function

I tried reading the below:

UIBarButtonItem is disabled, but has normal color

Change color of disabled bar button item in iOS

I'm able to change the color when it is not disabled. Seems when its disabled the colors are not obeyed?

KVISH
  • 12,923
  • 17
  • 86
  • 162
  • I am experiencing this bug too, it seems to only happen with Swift or maybe recent iOS versions. My work-around was to use a regular UIButton and init the UIBarButtonItem with that as a custom view. The the UIButton can be modified normally. – Siegfoult Sep 06 '17 at 18:11

1 Answers1

1

when its disabled the colors are not obeyed?

I hit this bug with some toolbar items. My workaround is to ensure that the UIBarButtonItem title changes at runtime, when the disabled color should change. To do this, change the disabled color, then force the title to change by adding an invisble Unicode space if needed.

For example in 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
}
Rick Andrews
  • 111
  • 1
  • 1
  • 4