Search code examples
iosswiftuinavigationcontrolleruinavigationitempresentviewcontroller

Swift: pass navigation bar through presentViewController


In my storyboard there are Navigation Controller, viewContrl1, and viewContrl2. For the next update, I have to make a way to segue viewContrl2 to another instance of viewContrl2.

After getting some helps from stackOverflow, I managed it via:

let newView2 : ViewContrl2 = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("viewContrl2") as! ViewContrl2
...
...
view2.presentViewController(newView2, animated: true, completion: nil)

It actually makes exactly what I want but without navigationBar on top. In ViewContrl2 class, there is @IBOutlet weak var navigation: UINavigationItem!, which I directly connected from StoryBoard. However, it seems like the navigation is not working in newly created viewContrl2. I need this because users must be able to press go back and go back to previous view. Anyone have any solution to this problem?

Thank you


Solution

  • To be able to go back, you need to use the existing Navigation controller. Just add a checking just to make sure.

    let newView2 : ViewContrl2 = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("viewContrl2") as! ViewContrl2
    
    if let navCtrl = self.navigationController
    {
       navCtrl.pushViewController(newView2, animated: true)
    }
    else
    {
       let navCtrl = UINavigationController(rootViewController: newView2)
       self.presentViewController(navCtrl, animated: true, completion: nil)
    }