Ariel Gemilang Ariel Gemilang - 1 year ago 127
Swift Question

found nil while unwrapping an Optional value when try to hidden navigation bar

I have a problem. I want to make if the cell tapped on 1st table view, it will display 2nd view controller and the navigation bar is hidden. Then i go back to 1st view controller using button with code:

@IBAction func backButtonTapped(sender: AnyObject) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let VC: UIViewController = storyBoard.instantiateViewControllerWithIdentifier("restaurant")
self.presentViewController(VC, animated: true, completion: nil)

but it print out

fatal error: unexpectedly found nil while unwrapping an Optional value

in 2nd view controller, I hidden the navigation bar using this:

func hiddenNavBar(){

self.navigationController!.navigationBar.hidden = true

and show the navigation bar again on 1st view controller using :

override func viewWillAppear(animated: Bool) {

func createNavBar(){

self.navigationController!.navigationBar.hidden = false

my Main storyboard looks like this:
enter image description here

Answer Source

You are using wrong way to go back to previous view controller. If you are using navigation view controller to push the second view controller then you need to pop view controller using self.navigationController?.popViewControllerAnimated(true)

How UINavigationViewController works? It creates a stack to keep track of all the view controllers you push that why if you want to go back, simply you need to pop view controller from the top as stack works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download