hikki
hikki

Reputation: 105

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

Upvotes: 2

Views: 5159

Answers (2)

Christian Abella
Christian Abella

Reputation: 5797

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)
}

Upvotes: 7

Mohammed Shakeer
Mohammed Shakeer

Reputation: 1504

If you want a NavigationBar to be seen, Please Present a NavigationController like Below:

let newView2 = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ViewContrl2") as! ViewContrl2

let navigationControlr = UINavigationController(rootViewController: newView2)

self.presentViewController(navigationControlr, animated: true, completion: nil)

To Dismiss the PresentedViewController add the following code in viewDidLoad

//Customise the way you want:
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "backAction")

add following function in your ViewController2 Class

func backAction(){

    if self.presentingViewController != nil{
        self.dismissViewControllerAnimated(true, completion: nil)
    }else{
        self.navigationController?.popViewControllerAnimated(true)
    }
}

Upvotes: 4

Related Questions