3

I am currently writing an app that uses embedded navigationControllers. I need to pop to the initial view of the first view controller from within the embedded one.

This line of code just returns me to the initial view of the embedded navigationController:

[self.navigationController popToRootViewControllerAnimated:YES];

Any ideas?

user3250926
  • 127
  • 1
  • 2
  • 7
  • 1
    Can you tell the hierarchy of you app and where do you want to pop ? – KudoCC Jan 29 '14 at 22:42
  • If figured it out. I just replaced [self.navigationController. popToRootViewControllerAnimated:YES]; with [self.navigationController.navigationController popToRootViewControllerAnimated:YES]; – user3250926 Jan 29 '14 at 23:09
  • navigationController property of UIViewController returns "The nearest ancestor in the view controller hierarchy that is a navigation controller". It seems you have two navigation controller that one is child controller of the other. – KudoCC Jan 29 '14 at 23:13

2 Answers2

6

You could do some recursive function like this. Name this whatever you would like or make it a category for convenience.

- (void)recursivePop:(UIViewController *)viewController
{
   if (viewController.navigationController)
   {
       [viewController.navigationController popToRootViewControllerAnimated:YES];
       [self recursivePop:viewController.navigationController];
   }
}

Then in the view controller you want to invoke this with call it like this.

[self recursivePop:self];
GregP
  • 1,584
  • 17
  • 16
0

Swift version:

func recursivePop(controller: UIViewController?){

    if let controller = controller {
        if let nav:UINavigationController = controller.navigationController {
            nav.popToRootViewControllerAnimated(true)
            self.recursivePop(controller)
        }

    if let split:UISplitViewController = controller.splitViewController {
            if let nav:UINavigationController = split.navigationController {
                nav.popToRootViewControllerAnimated(true)
                self.recursivePop(controller)
            }
        }
    }
}
odemolliens
  • 2,581
  • 2
  • 32
  • 34
  • 1
    Think this can be simplified by replacing the inner of the splitcontroller section with self.recursivePop(split) – GregP May 16 '16 at 17:08