@implementation UIView (SYGetController)
- (UIViewController *)currentController {
UIResponder *next = [self nextResponder];
do {
if ([next isKindOfClass:[UIViewController class]]) {
return (UIViewController *)next;
}
next = [next nextResponder];
} while (next != nil);
return nil;
}
@end
复制代码
+ (UIViewController *)currentViewController {
UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *currentVC = [self _findCurrentShowingViewControllerFromVC:vc];
return currentVC;
}
+ (UIViewController *)_findCurrentShowingViewControllerFromVC:(UIViewController *)vc {
UIViewController *currentVC;
if ([vc presentedViewController]) {
//判断当前根视图有没有present视图出来
UIViewController *nextVC = [vc presentedViewController];
currentVC = [self _findCurrentShowingViewControllerFromVC:nextVC];
} else if ([vc isKindOfClass:[UITabBarController class]]) {
//判断当前根视图是UITabBarController
UIViewController *nextVC = [(UITabBarController*)vc selectedViewController];
currentVC = [self _findCurrentShowingViewControllerFromVC:nextVC];
} else if ([vc isKindOfClass:[UINavigationController class]]) {
//判断当前根视图是UINavigationController
UIViewController *nextVC = [(UINavigationController *)vc visibleViewController];
currentVC = [self _findCurrentShowingViewControllerFromVC:nextVC];
}else {
currentVC = vc;
}
return vc;
}
复制代码
+ (UIViewController *)_findCurrentShowingViewControllerFromVC:(UIViewController *)vc {
while (1) {
if (vc.presentedViewController) {
vc = vc.presentedViewController;
} else if ([vc isKindOfClass:[UITabBarController class]]) {
vc = ((UITabBarController *)vc).selectedViewController;
} else if ([vc isKindOfClass:[UINavigationController class]]) {
vc = ((UINavigationController *)vc).visibleViewController;
} else if (vc.childViewControllers.count > 0) {
vc = vc.childViewControllers.lastObject;
} else {
break;
}
}
return vc;
}
复制代码
补充:presentedViewController
与 presentingViewController
假如从控制器A
经过present
方式跳转到B
,则A
的presentedViewController
就是B
,B
的presentingViewController
就是A
。bash