Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 663
hikki Avatar asked Feb 16 '26 14:02

hikki


2 Answers

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)
}
like image 72
Christian Abella Avatar answered Feb 19 '26 02:02

Christian Abella


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)
    }
}
like image 24
Mohammed Shakeer Avatar answered Feb 19 '26 04:02

Mohammed Shakeer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!