一、获取当前控制器的上一个控制器
#pragma mark - 获取当前控制器的上一个控制器
- (UIViewController *)getLastViewController {
NSInteger currentIndex = [self.navigationController.viewControllers indexOfObject:self];
if(currentIndex > 0 && currentIndex < self.navigationController.viewControllers.count && currentIndex != NSNotFound) {
// 获取上一个视图控制器
return [self.navigationController.viewControllers objectAtIndex:currentIndex - 1];
}
return nil;
}
二、删除上一个视图控制器
#pragma mark - 将当前控制器的上一个控制器从navigationController中移除
- (void)removeLastViewControllerFromNavigationController {
NSInteger currentIndex = [self.navigationController.viewControllers indexOfObject:self];
if(currentIndex > 0 && currentIndex < self.navigationController.viewControllers.count && currentIndex != NSNotFound) {
// 获取上一个视图控制器
UIViewController *lastVC = [self.navigationController.viewControllers objectAtIndex:currentIndex - 1];
// 删除上一个控制器(删除navigationController栈中得某一个viewController,方便跳过某一个vc而pop到更前面的vc)
NSMutableArray *viewControllers = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
for (UIViewController *vc in viewControllers) {
if ([vc isKindOfClass:[lastVC class]]) {
[viewControllers removeObject:vc];
break;
}
}
self.navigationController.viewControllers = viewControllers;
}
}
三、获取当前视图的控制器
#pragma mark - 返回当前视图的控制器
- (UIViewController *)getViewController {
for (UIView *next = [self superview]; next; next = next.superview) {
UIResponder *nextResponder = [next nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
return (UIViewController *)nextResponder;
}
}
return nil;
}
网友评论