How to Pop stack in IOS?

2019-09-02 08:52发布

问题:

I am building an iOS application.

What I am doing is explained below -

  1. There are 3 ViewControllers named as A, B, C.
  2. I go to A to B and then to C on button click function.
  3. I have to Implement Navigation controller on all three ViewController (A, B, C).
  4. Now, when I press back of navigation controller the stack that is followed is C -> B -> A. This is the default behavior.

What I need is the stack operation should be perform like - C -> A.

For this I have to Pop B from the stack. How can I Pop the B from stack.

回答1:

If your intention is to always go back to the first view controller on the stack, you can use

[self.navigationController popToRootViewControllerAnimated:YES];

If you want to pop X number of view controllers, check this answer from SO: How do I pop two views at once from a navigation controller?



回答2:

use below code to do this

NSArray *viewContrlls=[[self navigationController] viewControllers];
for( int i=0;i<[ viewContrlls count];i++){
  id obj=[viewContrlls objectAtIndex:i];
  if([obj isKindOfClass:[A class]]){
    // A is your class where to popback
    [[self navigationController] popToViewController:obj animated:YES];
    return;
    }
  }