环境:分别有ViewControllerA、ViewControllerB、ViewControllerC、ViewControllerD。
要实现的跳转顺序:ViewControllerA -> ViewControllerB -> ViewControllerC -> ViewControllerD,ViewControllerD直接跳回ViewControllerA。
在ViewControllerD中调用下面的方法。
可将该方法放到UIViewController的分类中,需要时直接调用:
/// 从导航栈中移除fromViewControllerClasses 到[self class]之间的VC
- (void)removeViewControllerFromNavigationStackWithStartControllerClasses:(NSArray *)startClasses {
for (int i = 0; i < startClasses.count; i++) {
Class startClass = startClasses[i];
BOOL flag;
flag = [self canRemoveViewControllerFromNavigationStackFrom:startClass to:[self class]];
if (flag) {
break;
}
}
}
/// 从导航栈中移除fromViewControllerClass 到 toViewControllerClass之间的VC
- (BOOL)canRemoveViewControllerFromNavigationStackFrom:(Class)fromClass
to:(Class)toClass {
NSMutableArray *viewControllers = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
// 将要删除的VC放到该数组中
NSMutableArray *removedVCs = [NSMutableArray array];
NSInteger fromIndex = -1;
NSInteger toIndex = -1;
/// 是否发现起始VC
BOOL flag = NO;
for (int i = 0; i < viewControllers.count; i++) {
UIViewController *vc = viewControllers[i];
if ([vc isKindOfClass:fromClass]) {
fromIndex = i;
flag = YES;
} else if ([vc isKindOfClass:toClass]) {
toIndex = i;
}
// 如果已发现起始VC,并且viewController不为要删除的VC时,记录到要删除的数组中
if (flag == YES &&
i != fromIndex &&
i != toIndex) {
[removedVCs addObject:vc];
}
}
if (flag == NO) {
return NO;
}
for (UIViewController *vc in removedVCs) {
[viewControllers removeObject:vc];
}
self.navigationController.viewControllers = viewControllers;
return YES;
}
网友评论