Reputation:
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
Reputation: 535
Two different solutions comes to my mind.
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