简体   繁体   中英

Hide Navigation Bar in Specific View - Swift 3

I have NavigationController that handles navigation through my app. According to my design, the very first view should have no visible NavigationBar. All the others after, will.

In this FirstView, I'm using this so far to hide the NavBar, inside the ViewDidLoad:

self.navigationController?.isNavigationBarHidden = true

From this FirstView I can access other Views. In these other views I show the NavBar using:

self.navigationController?.isNavigationBarHidden = false

My problem is that:

  • When I navigate from a View with Visible NavBar, back to the FirstView with the Hidden NavBar, the NavBar is now visible. Basically the NavBar only hides the very first time then shows if I use the back button.

How Can I Prevent this ?

Thank you!

Move that code to viewWillAppear() instead of viewDidLoad() .

viewDidLoad() is only called once per instantiated view controller, whereas viewWillAppear() is called whenever the view controller is about to be presented on screen.

You can read more about the view controller lifecycle here .

Write below code in your FirstViewController 's viewWillAppear method.

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated);
self.navigationController?.isNavigationBarHidden = true
}

And in your SecondViewController 's viewWillAppear method write below code

 override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated);
self.navigationController?.isNavigationBarHidden = false
}

Do not try to hide and show nav bar in viewWillAppear and viewWillDisappear subsequetly in FirstViewController .

You can use this function to hide NavigationBar with cool animation:

 func setupAnimationForNavigationBar(caseOfFunction: Bool) {
    if caseOfFunction == true {
        UIView.animate(withDuration: 0.5) {
            self.navigationController?.navigationBar.transform = CGAffineTransform(translationX: 0, y: -200)
        }
    } else {
        UIView.animate(withDuration: 0.5, animations: {
            self.navigationController?.navigationBar.transform = CGAffineTransform.identity
        })
    }

}

If you want to hide NavigationBar, so set it "True" and if you want to call NavigationBar again, set it "False"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM