3

I'm opening a navigation controller from a button click of my main view controller.

I programatically created a left bar button item on the navigation controller which I want to dismiss the nav controller and go back to my main controller.

I'm essentially going back on the root view controller of the navigation controller.

I've tried

navigationController?.dismissViewControllerAnimated(true, completion: nil)

and

self.dismissViewControllerAnimated(true, completion: nil)

and get an NSException on both.

Please advise.

matt
  • 515,959
  • 87
  • 875
  • 1,141
Walking
  • 467
  • 1
  • 7
  • 23

6 Answers6

9

Swift 3:

self.view.window!.rootViewController?.dismiss(animated: false, completion: nil)

It will dismiss all the presented view controllers and remain root view controller.

Umit Kaya
  • 5,771
  • 3
  • 38
  • 52
4

If you are pushing your ViewController, you should use pop to remove that ViewController from Navigation Stack and land on the previous ViewController. Try this...

self.navigationController?.popViewControllerAnimated(true);

SWIFT 3

_ = navigationController?.popViewController(animated: true);
Victor Rius
  • 4,566
  • 1
  • 20
  • 28
Suryakant Sharma
  • 3,852
  • 1
  • 25
  • 47
0

dismissViewController works when you are showing a viewController using presentViewController, that maybe the root view controller of a navigation stack, or a stand alone view controller.

Gaurav Pal
  • 141
  • 7
0
self.presentingViewController?.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)

Try this :)

Milap Kundalia
  • 1,566
  • 1
  • 16
  • 24
0

A year later.. The exception indicates that there is something wrong with the selector that you provide to the action param, when adding the left bar button.

Something like this should work:

creating bar button item:

let backBarButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.stop, target: self, action: #selector(dismissView))

dismiss root view controller:

func dismissView() {
    self.dismiss(animated: true, completion: nil)
}
PistolPete
  • 766
  • 3
  • 10
  • 25
0

Apple Dev already provides very simple code which is

self.navigationController?.popToRootViewController(animated: false)