美文网首页
查找当前控制器

查找当前控制器

作者: Fisher123 | 来源:发表于2017-06-23 10:54 被阅读15次
    //获取当前屏幕显示的viewcontroller
    - (UIViewController *)getCurrentVC {
        UIViewController *result = nil;
        UIWindow * window = [[UIApplication sharedApplication] keyWindow];
        //默认windowLevel是UIWindowLevelNormal
        if (window.windowLevel != UIWindowLevelNormal) {
            NSArray *windows = [[UIApplication sharedApplication] windows];
            for(UIWindow * tmpWin in windows) {
                if (tmpWin.windowLevel == UIWindowLevelNormal) {
                    window = tmpWin;
                    break;
                }
            }
        }
        id nextResponder = nil;
        UIViewController *appRootVC = window.rootViewController;
        if (appRootVC.presentedViewController) {
            nextResponder = appRootVC.presentedViewController;
        } else {
            UIView *frontView = [[window subviews] objectAtIndex:0];
            nextResponder = [frontView nextResponder];
        }
        if ([nextResponder isKindOfClass:[UITabBarController class]]){
            UITabBarController *tabbar = (UITabBarController *)nextResponder;
            UINavigationController *nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
            result = nav.childViewControllers.lastObject;
        } else if ([nextResponder isKindOfClass:[UINavigationController class]]){
            UIViewController *nav = (UIViewController *)nextResponder;
            result = nav.childViewControllers.lastObject;
        } else {
            result = nextResponder;
        }
        return result;
    }
    
    

    相关文章

      网友评论

          本文标题:查找当前控制器

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