Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismiss and Present View Controller in Swift

Hi I'm trying to present a viewcontroller and dismiss my current modal view but this code is not working

self.dismissViewControllerAnimated(true, completion: {
    let vc = self.storyboard?.instantiateViewControllerWithIdentifier("OrderViewController")
    self.presentViewController(vc!, animated: true, completion: nil)
})

vice versa is not working too on completion block of presentviewcontroller

EDIT: replaced vc! to self

like image 342
Ron Pelayo Avatar asked Jun 12 '16 05:06

Ron Pelayo


People also ask

How do I present and dismiss a view controller in Swift?

How did you present the view controller? I did the mapping by setting a segue - "show", see the attached screenshot. Try to use modal. If you use push, you should dismiss it with the pop method of the navigation controller.

How do you dismiss the presenting view controller?

When it comes time to dismiss a presented view controller, the preferred approach is to let the presenting view controller dismiss it. In other words, whenever possible, the same view controller that presented the view controller should also take responsibility for dismissing it.

How do I dismiss a view in Swift?

Any view can read its presentation mode using @Environment(\. presentationMode) , and calling wrappedValue. dismiss() on that will cause the view to be dismissed. The other option is to pass a binding into the view that was shown, so it can changing the binding's value back to false.


2 Answers

Here's a solution for Swift3

To present the ViewController

let NotificationVC = self.storyboard?.instantiateViewController(withIdentifier: "NotificationVC") as! ExecutiveNotificationViewController

self.present(NotificationVC, animated: true, completion: nil)

To dismiss the ViewController:

self.dismiss(animated: true, completion: nil)
like image 88
pansora abhay Avatar answered Sep 21 '22 17:09

pansora abhay


You have to get the viewController which presented self (current ViewController). If that view controller is rootViewController, then you can use the code below, if not then query it based on your view controller hierarchy.

if let vc3 = self.storyboard?.instantiateViewController(withIdentifier: "vc3") as? ViewController3 {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window?.rootViewController!.present(vc3, animated: true, completion: nil)
}
like image 20
Sandeep Kumar Avatar answered Sep 21 '22 17:09

Sandeep Kumar