Search code examples
iosswiftuinavigationcontrolleruinavigationbar

Custom Navigation Bar Subview does not hide when a new viewcontroller is pushed


So on my HomeViewController I added a custom Navigation Bar @IBOutlet weak var navBar: UIView! and I'm adding it to the navigation bar as:

self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.backgroundColor = .clear
self.navigationController?.view.insertSubview(navBar, belowSubview: navigationController!.view)
self.navigationController?.navigationBar.isTranslucent = false
self.edgesForExtendedLayout = []

Now when I push MenuViewController

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MenuVC") as! MenuViewController
self.navigationController?.pushViewController(vc, animated: true)

This custom navBar is still on the top. I want the default navigation bar to show again as I only want custom navBar on HomeViewController


Solution

    • You have added that custom navbar into the navigationController.view, that's why it will be seen on every viewController where navigationController is or will be used.

    You can do following to solve this

    • Add that navbar into subview of current UIView

    self.view.addSubview(navbar)

    • Hide the navigationBar from that particular UIViewController

    self.navigationController?.setNavigationBarHidden(true, animated: false)

    • show it to the next ViewController

    self.navigationController?.setNavigationBarHidden(false, animated: false)