ColorableNavigationController
is tiny subclass of UINavigationController
that supports different colors for navigation bars among different view controllers.
Code snippet was created to answer on my question at Stackoverflow.
Just add code from ColorableNavigationController.swift or copy that file to your project.
- Use
ColorableNavigationController
as your rootUINavigationController
(you can init it by yourself or change in Storyboard). - Adopt needed child view controllers to
NavigationBarColorable
protocol:
Colors will be set automatically on push or pop actions. Please don't forget to set initial values of barTintColor
and tintColor
on first load of UINavigationController
.
public protocol NavigationBarColorable: class {
var navigationTintColor: UIColor? { get } // optional
var navigationBarTintColor: UIColor? { get }
}
class ViewControllerA: UIViewController, NavigationBarColorable {
public var navigationBarTintColor: UIColor? { return UIColor.blue }
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Push", style: .plain, target: self, action: #selector(self.showController))
}
func showController() {
navigationController?.pushViewController(ViewControllerB(), animated: true)
}
}
class ViewControllerB: UIViewController, NavigationBarColorable {
public var navigationBarTintColor: UIColor? { return UIColor.red }
}
let navigationController = ColorableNavigationController(rootViewController: ViewControllerA())
Oh yeah, that's the stuff 🤤
Thanks