简体   繁体   中英

Set NavigationBar for Destination ViewController Only

I have a ViewController called SourceViewController that is embedded in a NavigationController.

SourceViewController segues to DestinationViewController upon UITableViewCell selection.

I want to hide the navigation bar on SourceViewController , but display it on DestinationViewController in order to show the Back button.

So, in SourceViewController :

override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationController?.navigationBar.hidden = true
}

And in DestinationViewController : override func viewDidLoad() { super.viewDidLoad()

    self.navigationController?.navigationBar.hidden = false
}

However, when I tap "Back" in DestinationViewController to return to SourceViewController , the navigationBar reappears in SourceViewController

The next 'obvious' step would be to set navigationBar.hidden = false in viewDidAppear in SourceViewController , however this smells for many reasons: mainly DRYness but also when returning to SourceViewController , there is a delay in hiding the navigationBar , and it is visible for a split second.

How do I solve this problem?

Check ViewController lifecycle Looking to understand the iOS UIViewController lifecycle . When you start the program viewDidLoad is called and everything is ok, but when you go back from detailController, viewDidLoad is not called, just change this line (self.navigationController?.navigationBar.hidden = true) in viewWillApear and everything must be ok.

I think this will work, hiding the navigation bar. before appearing/disappearing the view.

override func viewWillAppear(animated: Bool) {
    navigationController?.navigationBarHidden = true
    super.viewWillAppear(animated)
}


override func viewWillDisappear(animated: Bool) {
    navigationController?.navigationBarHidden = true
    super.viewWillDisappear(animated)
}

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