pmax1
pmax1

Reputation: 236

Swift Navigation Bar Color

Is it possible to set the navigation bar color for just a single View Controller in the navigation hierarchy? Let the default navigation bar color be red and just the last view controller in the line should have a blue one. I've used these two lines to color the navigation bar of said view controller:

navigationController?.navigationBar.barTintColor = .blue
navigationController?.navigationBar.tintColor = .white

But when going back (e.g. by pressing the back button) the navigation bar stays blue. Setting the color back to red using above code doesn't do anything.

Upvotes: 5

Views: 7483

Answers (2)

userx
userx

Reputation: 1121

I could get the navigation bar to change colors coming from a ViewControllerB to ViewControllerA perfectly fine with your code. I am not sure what your initial problem was. Here is my code which worked:

ViewController A:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.barTintColor = .red
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func buttonAction(_ sender: Any) {

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "Second")
        //self.present(controller, animated: true, completion: nil)
        self.navigationController?.pushViewController(controller, animated: true)
    }


}

ViewController B:

import UIKit

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.barTintColor = .blue
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

It worked without an issue.

Upvotes: 3

Ludovic Landry
Ludovic Landry

Reputation: 11784

The navigationBar is shared across all the view controllers that are in the same UINavigationController stack.

If you want to change it's look for a specific view controller, you'll have to set the new style when the view controller is shown and remove it when the view controller is dismissed. This could be done in the viewWillAppear/viewWillDisappear of your view controller for example.

Upvotes: 3

Related Questions