TWOF TWOF - 3 years ago 312
Swift Question

How do I style the backBarButtonItem title in a navigation bar?

I'd like to be able to change only the text color of the back button in the navigation bar.

As a work around, I can sort of do what I'm trying to do by creating a custom view and assigning it to

, but it doesn't look very good and I also lose the swipe to pop ability.
enter image description here

Code for the above:

let button = UIButton(type: .system)
let originalImage = #imageLiteral(resourceName: "BackButton")
let scaledImage: UIImage = UIImage(cgImage: originalImage.cgImage!, scale: 30, orientation: originalImage.imageOrientation)

button.setImage(scaledImage, for: .normal)
button.setTitle("YourTitle", for: .normal)
button.setTitleColor(.brown, for: .normal)
button.tintColor = .blue

navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)

I also see things suggested like setting attributes of the back button via

navigationController?.navigationBar.topItem.backBarButtonItem?.setTitleTextAttributes([NSForegroundColorAttributeName:], for: .normal)

but that doesn't seem to have any effect on the look of the text, despite

print("Attributes: ", navigationController?.navigationBar.topItem?.backBarButtonItem?.titleTextAttributes(for: .normal) ?? "No attributes")

resulting in
Attributes: ["NSColor": UIExtendedSRGBColorSpace 1 0 0 1]

I could set
but that would change the color of the back icon in addition to the title.

So what's the best way to do what I want? Is there a way?

Answer Source

I figured it out. You can style the back button by setting self.navigationItem.backBarButtonItem in the previous view controller.

For example, in my case I had TableViewController and when you clicked on a cell, the app would transition to ViewController. In TableViewController I had

public func changeColor() {
    let barButton = UIBarButtonItem(title: "Anything", style: .plain, target: nil, action: nil)
    barButton.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.brown], for: .normal)

    self.navigationItem.backBarButtonItem = barButton

and then in ViewController I had

@IBAction func buttonPressed(_ sender: Any) {
    let vc = self.navigationController?.viewControllers[0] as! TableViewController
    self.title = "hello very long title asdfasdfasfdasdfasdfasdfasdfasdf"

As a result, pressing a button in ViewController would change the color of the title of its back button to brown.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download