Popping multiple views from the navigation control

2019-05-07 03:00发布

I have an application which its rootview is a menu to 4 tableviews that the user uses to set up a search query by selecting a cell that loads another subview, so the basic structure looks like this

Root View
- Parent View (search view)
--Sub View (user selects variables here to fill search parameters of the parent view

But one of the Parent View search parameters requiers another sub view to be pushed onto the navigation stack so it would look like

Root View
- Parent View (search view)
--Sub View (user selects variables here to fill search parameters of the parent view
---Sub View (related values to the previous subview i.e. Model / sub model)

I would like to know if there is a way to pop back to the Parent View from this Sub View.. I know you can pop a single view or pop back to rootview but on this occasion I want to pop two subviews... is this possible?

2条回答
我只想做你的唯一
2楼-- · 2019-05-07 03:10

You can add a category to UINavigationController to allow multiple controllers to be popped at once.

UINavigationController+VariablePop.h

#import <UIKit/UIKit.h>

@interface UINavigationController (VariablePop)

- (NSArray *)popViewControllers:(int)numPops animated:(BOOL)animated;

@end

UINavigationController+VariablePop.m #import "UINavigationController+VariablePop.h"

@implementation UINavigationController (VariablePop)

- (NSArray *)popViewControllers:(int)numPops animated:(BOOL)animated {
    NSMutableArray* returnedControllers = [NSMutableArray array];
    int indexToPopTo = self.viewControllers.count - numPops - 1;
    for(int i = indexToPopTo+1; i < self.viewControllers.count; i++) {
        UIViewController* controller = [self.viewControllers objectAtIndex:i];
        [returnedControllers addObject:controller];
    }
    UIViewController* controllerToPopTo = [self.viewControllers objectAtIndex:indexToPopTo];
    [self popToViewController:controllerToPopTo animated:YES];
    return returnedControllers;
}

@end

And then from the view controller you can:

NSArray* poppedControllers = [self.navigationController popViewControllers:2 animated:YES];
查看更多
可以哭但决不认输i
3楼-- · 2019-05-07 03:12

UINavigationViewController

popToViewController:animated:

Pops view controllers until the specified view controller is at the top of the navigation stack.

- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated
查看更多
登录 后发表回答