1
votes

Sorry but none of the similar questions provide a working solution.

New single-view project. Storyboard actions:

  • VC1 is embedded in nav-controller
  • a button in VC1 activates a push seque into VC2
  • a button in VC2 activates a modal segue into VC3
  • VC3 has a button, and a UIViewController-subclass to handle the button action

Problem statement: How can I have the button of the modal VC3 close both VC3 and VC2 at once, taking me back to VC1?

This did not work - takes me to VC2 only:

- (IBAction)dismissPressed:(id)sender {
    UINavigationController *myNavController = [self navigationController];
    [self dismissViewControllerAnimated:NO completion:^{
        [myNavController popToViewController:[myNavController.viewControllers objectAtIndex:1] animated:NO];
    }];
}

Thank you very much!

3

3 Answers

0
votes

Ok guys, here is the solution:

If you can limit yourself to ios6+, the right answer is to make the button an unwind segue as described in What are Unwind segues for and how do you use them?

But if you are like me and must comply to ios5, the solution goes likes this:

In the VC who calls the modal segue declare a delegate like this:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"segueModalVC"]) {
        ModalVC *vc = [segue destinationViewController];
        vc.prevVC = self;
    }
}

You will have to #import the header for the destination modal VC.

Now in the modal VC itself add a property to hold the previous VC like this:

@property (weak, nonatomic) UIViewController *prevVC;

And now the button's action for popping both VCs should look like this:

- (IBAction)pressedMainMenu:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
    [[self.prevVC navigationController] popViewControllerAnimated:NO];
}

[EDITED to show the final version which works perfectly and can do flip animation from VC3 back to VC1. Took me hours to finalize this but now you can enjoy it for free :) ]

IMHO the fact that the modal VC has no 'native' method to access its preceding VC is a design bug.

0
votes

Use self.presentingViewController to find out the "previous view controller". You do not need to pass the previous view controller through the property.

- (IBAction)dismissPressed:(id)sender {
    UIViewController *presentingViewController = self.presentingViewController;
    [self dismissViewControllerAnimated:NO completion:^{
        [self.presentingViewController popViewControllerAnimated:TES];
    }];
}
0
votes

Try to Use popToRootViewControllerAnimated method to go back VC1.

- (IBAction)dismissPressed:(id)sender {
    UINavigationController *myNavController = [self navigationController];
    [self dismissViewControllerAnimated:NO completion:^{
        [myNavController popToRootViewControllerAnimated: NO];
    }];
}