Jake Jake - 3 years ago 212
iOS Question

Can't change UINavigationBar prompt color

I am unable to change the prompt color on my navigation bar. I've tried the code below in

, but nothing happens.

self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]

navigation bar image

Am I missing something? Is the code above wrong?

Answer Source

It seems like you're right about this one. You need to use UIAppearance to style the prompt text on iOS 11.

I've filed radar #34758558 that the titleTextAttributes property just stopped working for prompt in iOS 11.

The good news is that there are a couple of workarounds, which we can uncover by using Xcode's view hierarchy debugger:

Screenshot of UINavigation Bar Prompt on iOS 11

// 1. This works, but potentially changes *all* labels in the navigation bar. 
// If you want this, it works.
UILabel.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).textColor = UIColor.white

The prompt is just a UILabel. If we use UIAppearance's whenContainedInInstancesOf:, we can pretty easily update the color the way we want.

If you look closely, you'll notice that there's also a wrapper view on the UILabel. It has its own class that might respond to UIAppearance...

Screenshot of private UINavigationBar subview

// 2. This is a more precise workaround but it requires using a private class.

if let promptClass = NSClassFromString("_UINavigationBarModernPromptView") as? UIAppearanceContainer.Type
  UILabel.appearance(whenContainedInInstancesOf: [promptClass]).textColor = UIColor.white

I'd advise sticking to the more general solution, since it doesn't use private API. (App review, etc.) Check out what you get with either of these two solutions:

Properly colored prompt text

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download