環境:分別有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;
}