Search code examples
iosswiftuinavigationcontrolleruinavigationbar

setNavigationBarHidden doesn't work after setViewControllers


I found that setNavigationBarHidden doesn't work after setViewControllers?

This is my code:

  • HomeNavController.swift:

    class HomeNavController: UINavigationController {
    
        weak var tabBar: HomeTabBar!
    
        var tab: HomeTab = .match {
            didSet {
                switch self.tab {
                case .match:
                    self.setViewControllers([MatchViewController()], animated: false)
                case .moments:
                    self.setViewControllers([MomentsViewController()], animated: false)
                case .myPosts:
                    self.setViewControllers([PostsViewController()], animated: false)
                }
            }
        }
    }
    
  • MatchViewController.swift

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    

It works well when I first switch to MatchViewController instance, but it doesn't works after I change the HomeNavController instance's viewControllers with func setViewControllers.

Is it a bug of UINavigationController?


Solution

  • Maybe try setting the properties, this worked in my case:

        let navigationBarAppearance = UINavigationBar.appearance()
        let transparentColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0);
        // Sets the translucent background color
        navigationBarAppearance.backgroundColor = transparentColor
        navigationBarAppearance.titleTextAttributes = [NSForegroundColorAttributeName:transparentColor]
        // Hides the border
        navigationBarAppearance.shadowImage = UIImage()
        navigationBarAppearance.setBackgroundImage(UIImage(), for: .default)