swiftuinavigationcontrolleruinavigationitem

How to change the text color of rightBarButtonItem Item in Swift


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


Solution

  • 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)
    }