我有一个使用导航 Controller 的 iPhone 应用程序。在该 Controller 中我推送了一些 View 。在某些情况下,我想“清除” View 堆栈,只保留堆栈中导航 Controller 的 rootViewController 并推送我拥有的另一个 viewController 。
有人可以给我一个如何做到这一点的例子吗?我没有看到任何清除堆栈的方法。
<小时/>答案1: 我尝试在按钮操作中放入以下代码:
[self.navigationController popToRootViewControllerAnimated:NO];
do some stuff here to prepare for the push.
[self.navigationController pushViewController:self.myOtherController animated:YES];
但它只弹出到 roorController。它不会推送我想要的其他 viewController。
最佳答案
以下代码将允许用户深入 View 层次结构,并在按下按钮时弹出回 Root View Controller 并推送新 View 。
DetailViewController.m ~ 从中清除导航堆栈的 View Controller :
- (IBAction)buttonPressed:(id)sender {
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"popBack" object:nil]];
}
上面的代码调用 NSNotificationCenter
,发布一条通知,RootViewController 在听到时可以使用react。但首先,RootViewController 必须注册才能接收通知。
RootViewController.m
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushViews) name:@"popBack" object:nil];
[super viewDidLoad];
}
接下来,RootViewController 必须设置引用的选择器 -pushViews
。
- (void)pushViews {
//Pop back to the root view controller
[self.navigationController popToRootViewControllerAnimated:NO];
//Allocate and init the new view controller to push to
NewViewController *newVC = [[NewViewController alloc] init];
//Push the new view controller
[self.navigationController pushViewController:newVC animated:YES];
}
请确保在调用 -popToRootViewControllerAnimated:
时,为动画指定 NO
。启用动画会导致导航栏动画出现问题并使系统困惑。上面的代码在调用时会清除导航堆栈,只留下 RootViewController,然后添加 NewViewController。
您的初始代码未完全执行的原因是,从 DetailViewController 调用 -popToRootViewController:
后,RootViewController 的方法占用了主线程,并且 DetailViewController 被释放。因此,没有从该 View Controller 运行进一步的代码。使用上面的代码,导航堆栈将弹回到正在加载的同一 View Controller 。
关于iphone NavigationController 清除 View 堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10923732/