Search code examples
iosswiftuinavigationcontrolleruinavigationbar

UINavigationBar change colors on push


I'm using 2 different bar tint colors at UINavigationBar in different views. I'n changing color with that method in both views:

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

When I tap on back button color is not changed smoothly (you can see blink on last second).

Visual bug

But everything is okay if just swipe view back instead of tapping on back button.

No visual bug

How to make smooth transition in both situations?


Solution

  • I've coded final solution that looks most comfortable to use (don't need to use a lot of overrides in own view controllers). It works perfectly at iOS 10 and easy adoptable for own purposes.

    GitHub

    You can check GitHub Gist for full class code and more detailed guide, I won't post full code here because Stackoverflow is not intended for storing a lot of code.

    Usage

    Download Swift file for GitHub. To make it work just use ColorableNavigationController instead of UINavigationController and adopt needed child view controllers to NavigationBarColorable protocol.

    Example:

    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())