Wolfy
Wolfy

Reputation: 1465

iOS dismiss a chain of ViewControllers

I'm a bit puzzled by the following behavior in iOS (target is iPad with iOS 9.3 in Xcode 7.3.1). I have the following hierarchy:

Storyboard1
|
| initial
|
A (UIViewController)
|
| UIStoryboardSegue Present Modally
|
B (UINavigationController)
|
| root
|
C (UIViewController)
|
| presentViewController
|
Storyboard2
|
| initial
|
D (UIViewController)
|
| UIStoryboardSegue Present Modally
|
E (UIViewController) here

When E completes, I want to go back to A, so I thought about using self.navigationController?.dismissViewControllerAnimated(true, nil) in C, which I call from E by keeping a weak reference to C, but that brings me back to C and not A. If I want to go back to A I have to issue the same dismiss command twice. What am I missing?

Upvotes: 1

Views: 506

Answers (2)

stefos
stefos

Reputation: 1235

To dismiss multiple modals you can do this :

A.dismissViewControllerAnimated(true,nil)

Upvotes: 1

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

Wolfy,

Simply call,

UIApplication.sharedApplication().keyWindow?.rootViewController?.dismissViewControllerAnimated(true, completion: nil)

How it works

UIApplication.sharedApplication().keyWindow?.rootViewController will return `A (UIViewController)` 

since A ViewController has modally presented B (UINavigationController) and all other viewControllers are loaded in this navigation stack dismissing B (UINavigationController) will unload all the viewControllers for you :)

Happy coding :)

Upvotes: 1

Related Questions