user626776
user626776

Reputation:

how to change navigation bar color for the current view controller only

I am wondering how i can set the nav bar color for current VC only, without using viewWillAppear and viewWillDisappear pairs. These pair of functions are hard to maintain because it split the logic into 2 places.

I have seen multiple SO answers, but they change the whole navigation bar item throughout all VCs in the nav stack.

Upvotes: 0

Views: 1168

Answers (1)

Burak Akkaş
Burak Akkaş

Reputation: 535

Two different solutions comes to my mind.

  1. Implement custom NavigationBar for that ViewController
  2. Use a base ViewController to override NavigationBar color in each controller

I would prefer the second way, and here is an example:

class BaseViewController: UIViewController {
    
    // Set one color as default and override this property in each view controller that you want to change navigation bar color
    var navigationBarColor: UIColor {
        return .red
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.navigationController?.navigationBar.barTintColor = navigationBarColor
    }
}

class FirstViewController: BaseViewController {

    override var navigationBarColor: UIColor {
        return .blue
    }
    
    // Do your stuff
}

class SecondViewController: BaseViewController {
    
    override var navigationBarColor: UIColor {
        return .green
    }
    
    // Do your stuff
}

Upvotes: 2

Related Questions