Remove intermediate View Controllers from Navigation Stack - iOS

763 views Asked by At

I have a navigation stack as following:

VcA -> VcB -> VcC

When I press the back button on VcC navigationBar, I want to go to VcA.

I tried doing [self.navigationController popToRootViewControllerAnimated:YES] but it first pops to VcB and then goes to VcA.

I also tried this:

NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
[navigationArray removeObjectAtIndex: 1]; 
self.navigationController.viewControllers = navigationArray;

But it doesn't work. It still shows VcB first then shows VcA.

I tried both of the above code in viewWillDisappear of VcC.

Please help how can I solve this problem. Thanks

4

There are 4 answers

0
Paulw11 On BEST ANSWER

viewWillDisappear is too late to manipulate the view controller stack; the transition to view controller B is already underway. You should modify the stack using your second block of code in viewDidAppear so that when the back button is tapped the navigation controller transitions back to view controller A

0
jiten On

Try this:

for (UIViewController *controller in self.navigationController.viewControllers)
    {
        if ([controller isKindOfClass:[nameOfYourViewControllerYouWantToNavigate class]])
        {
            [self.navigationController popToViewController:controller animated:YES];

            break;
        }
    }
0
Annie Dev On

Try pop to root without animation, i.e [self.navigationController popToRootViewControllerAnimated:NO] –

0
oyvindhauge On

This is easily done by:

1. Getting an array of all controllers present in stack

NSArray *controllers = [self.navigationController viewControllers];

2. Then telling the navigation controller to pop to a controller at a specific index (e.g. 0):

[self.navigationController popToViewController:[controllers objectAtIndex:0] animated:YES];