Changing font color of UIBarButtonItem

寵の児 提交于 2020-06-11 16:53:07

问题


I tried to change the font color of the right bar button item to purple, but it still shows up as white. I've consulted this question and this question. How do I fix this?

Code

let sortButton = UIButton(frame: CGRect(x: 0, y: 0, width: 34, height: 15))
    sortButton.setTitle("SORT", for: .normal)
    sortButton.titleLabel?.tintColor = UIColor.myMusicPurple
    sortButton.tintColor = UIColor.myMusicPurple        
    navigationItem.rightBarButtonItem =  UIBarButtonItem(customView: sortButton)
    navigationItem.rightBarButtonItem?.tintColor = UIColor.myMusicPurple

回答1:


What about using:

func setTitleColor(UIColor?, for: UIControlState)

Documentation says it sets the color of the title to use for the specified state.

sortButton.setTitleColor( .red, for: .normal)



回答2:


This should do the trick (if you have plain text)

let rightBarButtonItem = UIBarButtonItem(title: "Some text", style: .plain, target: self, action: #selector(someAction))
rightBarButtonItem.tintColor = UIColor.myMusicPurple

navigationItem.rightBarButtonItem = rightBarButtonItem



回答3:


Its simple, just create a reference for UIBarButtonItem from Main.stroyboard to corresponding swift file like this,

@IBOutlet var yourBarBtn: UIBarButtonItem!

After that write this line,

yourBarBtn.tintColor = .white //your_color

Thats it!




回答4:


Please try this

sortButton.setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.white], for: .normal)



回答5:


First, you need to set plain properties then after you can write as like.

  @IBOutlet weak var btnGenerate: UIBarButtonItem!

  btnGenerate.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.colorBlue], for: .normal)


来源:https://stackoverflow.com/questions/44893174/changing-font-color-of-uibarbuttonitem

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