Search code examples
swiftuinavigationcontrollerpushviewcontroller

Why is hidesBottomBarWhenPushed not working when not root view controller?


A view controller is pushed and the bottom tab bar is hidden like so:

let myViewController = self.storyboard?.instantiateViewController(withIdentifier: MyViewController) as! MyViewController 
myViewController.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(myViewController, animated: true)

That works fine.

However when I change the root view controller before the push the bottom bar is not hidden.

// Change the root view controller
let firstRootViewController = UIApplication.shared.keyWindow!.rootViewController
UIApplication.shared.keyWindow!.rootViewController = secondRootViewController

// Push view on stack of navigation controller which is a child of firstRootViewController
let myViewController = self.storyboard?.instantiateViewController(withIdentifier: MyViewController) as! MyViewController 
myViewController.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(myViewController, animated: true)

// Some more things happen...

// Switch back to previous root view controller
UIApplication.shared.keyWindow!.rootViewController = firstRootViewController

The result is that the navigation controller pushed the myViewController correctly but the bottom bar is visible, as if the parameter hidesBottomBarWhenPushed was ignored.

What's wrong here?


Solution

  • The solution was to not change the root view controller but to only add the view to the keyWindow:

    // Add another view on top of all views
    UIApplication.shared.keyWindow?.addSubView(self.view)
    
    // Push view on stack of navigation controller which is a child of firstRootViewController
    let myViewController = self.storyboard?.instantiateViewController(withIdentifier: MyViewController) as! MyViewController 
    myViewController.hidesBottomBarWhenPushed = true
    navigationController?.pushViewController(myViewController, animated: true)
    
    // Some more things happen...
    
    // Remove topmost view
    self.view.removeFromSuperview()