Changing navigation bar color while popping view controller

后端 未结 5 869
盖世英雄少女心
盖世英雄少女心 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:57

    Another solution that works is overriding pushViewController(_ viewController: UIViewController, animated: Bool) and popViewController(animated: Bool) -> UIViewController? of UINavigationController.

    class CustomNC : UINavigationController {
        public override init(rootViewController: UIViewController) {
            super.init(rootViewController: rootViewController)
        }
    
        public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
            super.init(nibName: nil, bundle: nil)
        }
    
        public required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        private var isCustomDesign: Bool { 
            return viewControllers.count == 1 && viewControllers[0] is MyCustomVC // Or any other condition 
        }
    
        override func pushViewController(_ viewController: UIViewController, animated: Bool) {
            super.pushViewController(viewController, animated: animated)
            if isCustomDesign {
                navigationBar.barTintColor = UIColor.red
            } else {
                navigationBar.barTintColor = UIColor.green
            }
        }
    
        override func popViewController(animated: Bool) -> UIViewController? {
            let viewController = super.popViewController(animated: animated)
            if isCustomDesign {
                navigationBar.barTintColor = UIColor.red
            } else {
                navigationBar.barTintColor = UIColor.green
            }
            return viewController
        }
    }
    

提交回复
热议问题