Search code examples
iosobjective-cuiviewcontrolleruinavigationcontrollerstoryboard

Back to RootViewController from Modal View Controller


From Home view - my RootViewController - I open up 2 ViewControllers one after another as user progresses in navigation hierarchy like so:

1) SecondViewController is pushed by button connected in my Storyboard

2) ThirdViewController is presented modally

[self performSegueWithIdentifier:@"NextViewController" sender:nil];

So, the picture is: RootViewController -> SecondViewController -> ThirdViewController

Now in my ThirdViewController I want to have a button to go back 2 times to my RootViewController, i.e. go home. But this does not work:

[self.navigationController popToRootViewControllerAnimated:YES]; 

Only this guy goes back once to SecondViewController

[self.navigationController popViewControllerAnimated:YES];

How can I remove both modal and pushed view controllers at the same time?


Solution

  • I had a similar situation, where I had a number of view controllers pushed onto the navigation controller stack, and then the last view was presented modally. On the modal screen, I have a Cancel button that goes back to the root view controller.

    In the modal view controller, I have an action that is triggered when the Cancel button is tapped:

    - (IBAction)cancel:(id)sender
    {
        [self.delegate modalViewControllerDidCancel];
    }
    

    In the header of this modal view controller, I declare a protocol:

    @protocol ModalViewControllerDelegate
    - (void)modalViewControllerDidCancel;
    @end
    

    And then the last view controller in the navigation stack (the one that presented the modal view) should implement the ModalViewControllerDelegate protocol:

    - (void)modalViewControllerDidCancel
    {
        [self dismissViewControllerAnimated:NO completion:nil];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    

    This method above is the important part. It gets the presenting view controller to dismiss the modal view, and then it pops back to the root view controller. Note that I pass NO to dismissViewControllerAnimated: and YES to popToRootViewControllerAnimated: to get a smoother animation from modal view to root view.