[英]How to dismiss a view controller in a navigation controller, without dismissing the whole stack
[英]How to dismiss a whole stack of view controllers in navigation view controller?
我有兩個導航視圖控制器。當我單擊屬於第二個導航控制器的ViewController中的按鈕時,我想關閉該導航控制器的整個視圖控制器堆棧,並想轉到第一個導航控制器中的視圖控制器。我怎樣才能做到這一點? 我試過[self.navigationController dismissViewControllerAnimated:YES completion:nil];
似乎什么也沒有發生。如何執行此操作?
該錯誤必須在其他地方。 您所描述的代碼確實有效。 我創建了一個新項目,並給出了一個非常簡單的示例:
#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
是否為nil。
試試這個,我認為它對你有用
self.navigationController?.popToRootViewController(animated: true)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.