Reputation: 5754
In iOS 4, if you want to dismiss two nested modal view controllers, the following code works:
[[[[self parentViewController] parentViewController] parentViewController] dismissModalViewControllerAnimated:YES];
However in iOS 5 this method no longer works. Does anybody know how to achieve this result in iOS 5?
Upvotes: 4
Views: 6605
Reputation: 19642
For a stack of two modals call this baby from your delegate method on the initial presenter to jump back down the stack and nuke the presented VCs.
[self.presentedViewController.presentedViewController dismissViewControllerAnimated:NO completion:nil];
[self.presentedViewController dismissViewControllerAnimated:YES completion:nil];
Obviously it's a bit brittle because if you start adding more modals then things will break. Generally if you're doing a stack of controllers you would use UINavigationController, but for a couple of modals this does the trick and is a lot less complex than setting up notifications or even more delegates!
Upvotes: 0
Reputation: 910
If you call dismissViewControllerAnimated: on the view controller that presented the first modal, you'll dismiss of both modals at once. So in your 2nd modal you would do the following:
[self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:NULL];
Upvotes: 11
Reputation: 7976
I have an app that closes nested modal view controllers through NSNotificationCenter. The notification is received by the VC that I want to navigate back to and all the VC's in between are gone.
In the deeper VC...
NSNotification * notification = [NSNotification notificationWithName:@"BACKTOINDEXNOTE" object:nil];
[[NSNotificationCenter defaultCenter] postNotification:notification];
In the VC I would like to go back to
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismiss) name:@"BACKTOINDEXNOTE" object:nil];
// more init code
}
return self;
}
-(void)dismiss
{
[self dismissModalViewControllerAnimated:YES];
}
This works on iOS 5 device with a project deployed for 4.0+ I hope it helps. If you use this, it will scale to support more VC's in between your current VC and the one you want to dismiss to, without changing this code
Upvotes: 8