How to change the text color of rightBarButtonItem Item in Swift

110 Views Asked by At

I am trying to change the text color of the rightBarButtonItem item text and it blue by default . I am trying to change it to black .

My current code for that is:

self.navigationItem.rightBarButtonItem?.tintColor = .black

This does not change anything and the text color is the same . Added the cancel rightBarButtonItem image that i need to change the text from blue to black. How can i do that enter image description here

2

There are 2 best solutions below

7
Leo Dabus On BEST ANSWER

Make sure to initialize your rightBarButtonItem before setting its tint color otherwise your optional biding will fail silently:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    navigationItem.rightBarButtonItem = .init(
        barButtonSystemItem: .cancel,
        target: self,
        action: #selector(cancelAction)
    )
    navigationItem.rightBarButtonItem?.tintColor = .black
}

@objc func cancelAction(_ barButtonItem: UIBarButtonItem) {
   print(#function)
}
3
Abhishek Biswas On

first make a outlet of Bar button item if using storyboard like

@IBOutlet weak var menuBtn:UIBarButtonItem!

at ViewDidLoad() function write this code which will change the tint colour of bar button aka text colour

self.menuBtn.tintColor = .red

This will chnage the tint colour of text.

if using programatically then you can do this. first embead the view controller in navigation controller. and at the viewDidLoad() function. you can code this.

@overide func viewDidLoad(){
   super.viewDidLoad()
   self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "editor", style: .done, target: self, action: #selector(someAction(_ :)))
   self.navigationItem.rightBarButtonItem?.tintColor = .green
} 

This will change the tint colour of the bar button item into green