- 首先,获取当前window的rootViewController;
- 然后,循环遍历 rootViewController 并判断其类型(UINavigationController、UITabBarController、rootVC.childViewControllers),根据其类型不同,找到visibleViewController,结束。
代码如下:
+ (UIViewController *)currentActiveController {
UIWindow *window = [UIApplication sharedApplication].delegate.window;
MADLog(@"windowLevel: %.0f", window.windowLevel);
if (window.windowLevel != UIWindowLevelNormal) {
NSArray *windows = [[UIApplication sharedApplication] windows];
for (UIWindow * tmpWin in windows) {
if (tmpWin.windowLevel == UIWindowLevelNormal) {
window = tmpWin;
break;
}
}
}
UIViewController *rootVC = window.rootViewController;
UIViewController *activeVC = nil;
while (true) {
if ([rootVC isKindOfClass:[UINavigationController class]]) {
activeVC = [(UINavigationController *)rootVC visibleViewController];
} else if ([rootVC isKindOfClass:[UITabBarController class]]) {
activeVC = [(UITabBarController *)rootVC selectedViewController];
} else if (rootVC.presentedViewController) {
activeVC = rootVC.presentedViewController;
} else if (rootVC.childViewControllers.count > 0) {
activeVC = [rootVC.childViewControllers lastObject];
} else {
break;
}
rootVC = activeVC;
}
return activeVC;
}
网友评论