@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