美文网首页
iOS 获取当前屏幕显示的viewcontroller

iOS 获取当前屏幕显示的viewcontroller

作者: 彼岸花下的暗影 | 来源:发表于2019-05-24 14:45 被阅读0次
//获取当前屏幕显示的viewcontroller 
- (UIViewController *)getCurrentVC {
    
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    
    //寻找当前显示的window    (若项目只有一个window  可省略)
    if (window.windowLevel != UIWindowLevelNormal)  {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)  {
            
            if (tmpWin.windowLevel == UIWindowLevelNormal)  {
                
                window = tmpWin;
                break;
            }
        }
    }
    
    UIViewController *root = window.rootViewController;
    
    while (root) {
        if ([root isKindOfClass:[UITabBarController class]]) {
            UITabBarController *tab = (UITabBarController *)root;
            root = tab.selectedViewController;
        }
//        else if ([root isKindOfClass:[GKNavigationController class]]){
//            root = ((GKNavigationController *)root).gk_topViewController;
//        }
        else if([root isKindOfClass:[UINavigationController class]]) {
            root = root.childViewControllers.lastObject;
        }
        else if (root.presentedViewController){
            root = root.presentedViewController;
        }
        else{
            result = root;
            root = nil;
        }
    }
    return result;
}

相关文章

网友评论

      本文标题:iOS 获取当前屏幕显示的viewcontroller

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