考虑:
[self.navigationController popToViewController:[[self.navigationController viewControllers]objectAtIndex:1] animated:YES];
有没有更好的方法让视图控制器的索引弹出?这样,如果我对导航堆栈执行某些操作,我就不必返回并编辑它。我想的可能是将它存储在VC上的ivar中或使用#define宏。有什么想法吗?
修改 该堆栈有四个视图控制器。我用这个代码从第四个到第二个弹出。
答案 0 :(得分:5)
YourViewController *yourViewController;
for ( UIViewController *viewController in self.navigationController.viewControllers ) {
if ( [viewController isMemberOfClass:[YourViewController class]] ) {
yourViewController = (YourViewController*)viewController;
break;
}
}
[self popToViewController:yourViewController animated:YES];
当然,这假设堆栈只有一个您正在寻找的控制器类的实例。如果还有更多,我认为您可以选择将其存储在全局可访问的位置,例如应用程序委托。
注意 - 通常如果您在UIViewController中使用它,那么最后一行代码将是:
[self.navigationController popToViewController:seuleMainPage animated:YES];
答案 1 :(得分:4)
您可以使用UINavigationController
上的简单类别替换问题中的代码,该类别可以在适当的地方使用。
@interface UINavigationController(indexPoping)
- (void)popToViewControllerAtIndex:(NSInteger)newVCsIndex animated:(BOOL)animated;
@end
@implementation UINavigationController(indexPoping)
- (void)popToViewControllerAtIndex:(NSInteger)newVCsIndex animated:(BOOL)useAnimation
{
if (newVCsIndex < [self.viewControllers count]) {
[self popToViewController:[self.viewControllers objectAtIndex:newVCsIndex] animated:useAnimation];
}
}
// Usage
...
NSInteger indexToPopTo = ...
[self.navigationController popToViewControllerAtIndex:indexToPopTo animated:YES]
...
答案 2 :(得分:0)
只需使用isKindOfClass
[self.navigationController.viewControllers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if([obj isKindOfClass:[YourViewController class]]) {
YourViewController *objVC = obj;
[self.navigationController popToViewController:objVC animated:YES];
*stop = YES;
}
}];