How can I pop to any view controller as I wish?

180 views Asked by At

view controller A B C D A -> B -> C-> D popViewController only form D to C popViewTopController only form D to A; Any way can I pop to any view as I wish if I have 10 view controllers?

Thanks for everyone. will the popViewController pop to a new view Controller ?

5

There are 5 answers

0
sohil On BEST ANSWER

if you want to pop any view you want to change objectAtIndex:1,2,3..etc it will pop to first,second etc... from the any views.

[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
0
Daniel On

Option 1: Select by class

To tell the navigationController to pop to a specific class, you can do as follows:

NSArray *allViewControllers = [self.navigationController viewControllers];
for (UIViewController *aViewController in allViewControllers) 
{
  if ([aViewController isKindOfClass:[B class]]) 
  {
    [self.navigationController popToViewController:aViewController animated:YES];
  }
}

Take into account that you should only use this, if you are not pushing instances of the same class several times.

Option 2: Select by level

If you want to pop to a specific level, you can just select it by index at self.navigationController.viewControllers since it correspond to the levels. The first pushed UIViewController will be at index 0, the second at index 1 and so on:

NSArray *allViewControllers = [self.navigationController viewControllers];
UIViewController *aViewController = [allViewControllers objectAtIndex:level];
[self.navigationController popToViewController:aViewController animated:YES];
0
Nilesh Parmar On
SecondViewController *sec = [SecondViewController alloc] init];
[self.navigationController popViewController:Sec animated:YES];
0
Tristan Burnside On

This is the method you are looking for (reference)

In Obj-c

- (NSArray *)popToViewController:(UIViewController *)viewController
                    animated:(BOOL)animated

You should pass in the view controller that you want pop to

0
brianpseudo On

Use the following UINavigationController method to go to any view controller on the current stack.

- (NSArray *)popToViewController:(UIViewController *)viewController 
                        animated:(BOOL)animated

For example, if you are in a UIViewController and you want to pop back to the third one in the stack:

UINavigationController * nc = self.navigationController;
UIViewController * popToVC = [nc.viewControllers objectAtIndex:2];
[nc popToViewController:popToVC animated:YES];