19

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
Alex
  • 2,369
  • 3
  • 13
  • 23

5 Answers5

36

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
Kristijan Delivuk
  • 1,253
  • 13
  • 24
10

Please try this

sortButton.setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.white], for: .normal)
Faysal Ahmed
  • 7,501
  • 5
  • 28
  • 50
Avinash
  • 4,304
  • 1
  • 23
  • 18
7

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

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

enter image description here

  @IBOutlet weak var btnGenerate: UIBarButtonItem!

  btnGenerate.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.colorBlue], for: .normal)
kalpesh
  • 1,285
  • 1
  • 17
  • 30
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)
Refactor
  • 524
  • 1
  • 11
  • 20
  • 9
    This shouldn't be the accepted answer. `UIBarButtonItem` doesn't have `setTitleColor`. The correct answer is to use `tintColor`. – JaredH Mar 26 '19 at 21:04