Changing navigation bar color while popping view controller

后端 未结 5 951
盖世英雄少女心
盖世英雄少女心 2020-12-30 02:58

I have three view controllers. In the first view controller (FirstVC), the navigation bar\'s bar tint color is clearColor and the bar itself is translucent. When I click on

5条回答
  •  粉色の甜心
    2020-12-30 03:53

    Came across this thread and came up with a nice solution to help all in the future.

    Firstly create a custom UINavigationController with a type enum that will help define your navigation setups:

    enum NavType: Int {
        case light, medium, dark
    }
    
    class NavigationController: UINavigationController {
    
        /* 
          Fetch the last controller in the navigation stack so the 
          ViewControllers can switch the navType
        */
        var previousController: ViewController? {
            if viewControllers.count > 1 {
                return viewControllers[viewControllers.count-2] as? ViewController
            }
            return nil
        }
    
        var navType: NavType = .light {
            didSet { updateNavType() }
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
            navigationBar.isTranslucent = false
            layoutNavigationTheme()
        }
    
        func layoutNavigationTheme() {
            switch navType {
            case .dark:
                view.backgroundColor = .white
                navigationBar.backgroundColor = .black
                navigationBar.barTintColor = .black
                navigationBar.tintColor = .white
    
            ... // Set up as per enum
            }
        }
    
    }
    

    Then create a custom UIViewController using the willMove(...:

    class ViewController: UIViewController {
    
        var navType: NavType = .light
    
        var navigation: NavigationController? {
            return navigationController as? NavigationController
        }
    
        // Override willMove will fetch the last controller and set the navType
        override func willMove(toParentViewController parent: UIViewController?) {
            super.willMove(toParentViewController: parent)
    
            if let navigation = navigation {
                navigation.navType = navigation.previousController?.navType ?? .light
            }
        }
    
    }
    

    Then simply in your UIViewControllers, subclass your new ViewController and set the navType in the viewDidLoad:

    class MainController: ViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            navType = .dark
        }
    
    }
    

提交回复
热议问题