简体   繁体   中英

iOS 13 UIBarButtonItem color in dark mode

My UIBarButtonItem image doesn't change its color when switching between dark and light mode.

I set the color programmatically and expected it to change between black and white when switching the mode. At least it works with the tintColor of my NavigationBar.

I set:

myBarButton.tintColor = UIColor.white

and the image of the button stays white in dark AND in light mode.

On the other hand, the following is black in light mode and white in dark mode:

navigationBar.tintColor = UIColor.white

Why does it behave differently and how can I add this functionality to my UIBarButtonItem?

UIColor.white is not a dynamic color. It will be white regardless of the appearance setting. If you want a color that is different depending on the appearance, you need to take one of the new dynamic system colors (eg, UIColor.systemBackground would be white in light and black in dark mode), or create a color asset with different color values for light and dark appearance in an asset catalog.

Here is more on the new system colors: https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/color#dynamic-system-colors

Using iOS 13's new appearance API: https://developer.apple.com/documentation/uikit/uinavigationbarappearance

Example:

let navStyle = UINavigationBarAppearance()

let buttonStyle = UIBarButtonItemAppearance()
// Change properties of buttonStyle here with dynamic colours such as UIColor.label.
style.buttonAppearance = buttonStyle
style.doneButtonAppearance = ...
style.backButtonAppearance = ...

navigationController?.navigationBar.standardAppearance = navStyle
navigationController?.navigationBar.scrollEdgeAppearance = ...
navigationController?.navigationBar.compactAppearance = ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM