美文网首页
iOS 获取当前显示的Controller(OC实现)

iOS 获取当前显示的Controller(OC实现)

作者: 大成小栈 | 来源:发表于2020-09-25 14:15 被阅读0次
  1. 首先,获取当前window的rootViewController;
  2. 然后,循环遍历 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;
}

相关文章

网友评论

      本文标题:iOS 获取当前显示的Controller(OC实现)

      本文链接:https://www.haomeiwen.com/subject/ccrfuktx.html