Bar Button Item Tint Color not working

谁都会走 提交于 2021-02-10 18:14:36

问题


As you can see in the attached image, the bar button has its tint color set to red, however it is displayed in black. I think this is due to the text color still being black? Is there a way to change this?

I changed the tint color of this bar button item, the navigation bar it is in, and the UIBarButtonItem.appearance(), as well as UINavigationBar.appearance(). Closing the popover and reopening it changes the color.

EDIT

In the hierarchy below the bar button has the correct tint color (no text), the label has correct tint and text colors however the label has different tint and text colors. Text color is still the one from the old theme and does not update until the view is dismissed and reopened.

However holding down the button causes it to flash in the new color, and then fade back to normal.


回答1:


Here is a piece of code I use to style UIBarButtonItem:

extension UIBarButtonItem {

   func style(tint color: UIColor, font f: UIFont? = nil) {
       let font = f ?? UIFont.systemFont(ofSize: UIFont.systemFontSize)
       tintColor = color
       let atts = [
           NSAttributedStringKey.font : font,
           NSAttributedStringKey.foregroundColor : color
       ]
       setTitleTextAttributes(atts, for: .normal)
   }

}

This should've been the end of it but attempting to change the title attributes and tint color repeatedly (e.g. on button action) reveals nothing happens unless the bar button item's title changes. This is weird behaviour but an easy workaround will be to do just that, change the title by adding and removing extra space at the end of the title like:

// Hack!!! adds and removes an empty space to the title to 
// force the bar item reset title attributes.
let title: String = barItem.title ?? ""
barItem.title = title.hasSuffix(" ") ? String(title.dropLast()) : title + " "


来源:https://stackoverflow.com/questions/48975439/bar-button-item-tint-color-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!