如何在导航视图控制器中关闭整堆视图控制器?

时间:2017-08-04 06:29:54

标签: ios objective-c uiviewcontroller uinavigationcontroller

我有两个导航视图控制器。当我点击属于第二个导航控制器的ViewController中的按钮时,我想要关闭该导航控制器的完整视图控制器堆栈并想要在第一个中转到视图控制器导航控制器。我怎么能这样做?我试过[self.navigationController dismissViewControllerAnimated:YES completion:nil];似乎什么都没发生。怎么做?

2 个答案:

答案 0 :(得分:1)

错误必须在其他地方。您描述的代码确实可以使用。我创建了一个新项目并制作了一个非常简单的例子:

#import "ViewController.h"

@interface MyViewController : UIViewController
- (instancetype)initWithColor:(UIColor *)color;
@end


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:[[MyViewController alloc] initWithColor:[UIColor redColor]]] animated:YES completion:nil];
}

@end



@implementation MyViewController

- (instancetype)initWithColor:(UIColor *)color {
    if((self = [super init])) {
        self.view.backgroundColor = color;
    }
    return self;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    CGPoint point = [touches.anyObject locationInView:nil];
    if(point.x < self.view.frame.size.width*0.5 && point.y < self.view.frame.size.width*0.5) {
        [self.navigationController pushViewController:[[MyViewController alloc] initWithColor:self.view.backgroundColor] animated:YES];
    } else if(point.x > self.view.frame.size.width*0.5 && point.y < self.view.frame.size.width*0.5) {
        [self.navigationController presentViewController:[[UINavigationController alloc] initWithRootViewController:[[MyViewController alloc] initWithColor:[UIColor greenColor]]] animated:YES completion:nil];
    } else if(point.x < self.view.frame.size.width*0.5 && point.y > self.view.frame.size.width*0.5) {
        [self.navigationController popViewControllerAnimated:true];
    } else if(point.x > self.view.frame.size.width*0.5 && point.y > self.view.frame.size.width*0.5) {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}

@end

如果将其复制到一个新项目中,ViewController是您的主视图控制器,将创建一个导航控制器,并在视图上显示。背景为红色。

按下屏幕的左上角,相同颜色的新控制器将被推送到当前的顶部导航控制器。

按右上方的新导航控制器将显示绿色视图控制器。

按左下角可以弹出当前视图控制器(如果有)。

按下右下角,您将关闭顶部导航控制器。

所以你的情况是按左上角几次在一个导航控制器上生成一堆视图控制器。然后按右上方显示另一个导航控制器(绿色)。在左上角按几次,在绿色导航控制器上创建一堆几个视图控制器。现在按下右下方以关闭整个绿色堆栈并返回红色导航控制器堆栈。

请仔细检查您的代码,看看您的案例中发生了什么,为什么您遇到问题。首先检查self.navigationController是否为零。

答案 1 :(得分:-2)

尝试这个我觉得它适合你

self.navigationController?.popToRootViewController(animated: true)