.h文件
/**
移除当前导航控制器栈中的控制器
@param coordinateVC 坐标控制器,表示是从哪个控制器开始移除
【案例用法】比如从A push B, B push C, C push D, 现在需要你从D pop 到 A, 要达到这样的效果, 则在D调pop方法之前, 在 D控制器下调下面的方法先移除BC两个控制器,此时(coordinateVC传self,removeIndex传1,表示从D上removeIndex个控制器移除,removeLength )
*/
+ (void)kl_removeCurrenStackVCWithCoordinateVC:(UIViewController *)coordinateVC
removeIndex:(NSUInteger)removeIndex
removeLength:(NSUInteger)removeLength;
/**
* 获取当前视图的控制器
*/
+ (UIViewController *)kl_getCurrentVC;
.m文件
#import "UIViewController+Extension.h"
@implementation UIViewController (Extension)
+ (void)kl_removeCurrenStackVCWithCoordinateVC:(UIViewController *)coordinateVC
removeIndex:(NSUInteger)removeIndex
removeLength:(NSUInteger)removeLength
{
if (!coordinateVC.navigationController) {
return;
}
NSMutableArray *vcArray = coordinateVC.navigationController.childViewControllers.mutableCopy;
NSInteger coordinateVCIndex = [vcArray indexOfObject:coordinateVC];
if (coordinateVCIndex == NSNotFound) {
return;
}
if (coordinateVCIndex < removeIndex + removeLength) { // 导航控制器栈里面至少留一个控制器
return;
}
NSRange range = NSMakeRange(coordinateVCIndex - removeIndex - removeLength + 1, removeLength);
NSLog(@"哈哈哈哈: %ld-%ld", range.location, range.length);
[vcArray removeObjectsInRange:range];
[coordinateVC.navigationController setViewControllers:vcArray];
}
+ (UIViewController *)kl_getCurrentVC {
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
return currentVC;
}
+ (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC {
UIViewController *currentVC;
if ([rootVC presentedViewController]) { // 视图是被presented出来的
rootVC = [rootVC presentedViewController];
}
if ([rootVC isKindOfClass:[UITabBarController class]]) { // 根视图为UITabBarController
currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
}else if ([rootVC isKindOfClass:[UINavigationController class]]) { // 根视图为UINavigationController
currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
}else { // 根视图为非导航类
currentVC = rootVC;
}
return currentVC;
}
@end
网友评论