美文网首页
iOS获取当前显示的UIViewController

iOS获取当前显示的UIViewController

作者: 跑调的安眠曲 | 来源:发表于2016-03-08 17:59 被阅读747次

    当我们在前台收到远程推送,或者需要封装一个兼容iOS9之后的UIAlertController的弹出警告框等等场景时,我们需要去获取当前屏幕显示的UIViewController,具体方法如下:

    //获取当前屏幕显示的UIViewController  
    - (UIViewController *)getCurrentVC {
        UIViewController *result = nil;  
        
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        if (window.windowLevel != UIWindowLevelNormal) {
            NSArray *windows = [[UIApplication sharedApplication] windows];  
            for(UIWindow *tmpWin in windows) {
                if (tmpWin.windowLevel == UIWindowLevelNormal) {
                    window = tmpWin;  
                    break;  
                }  
            }  
        }  
        
        UIView *frontView = [[window subviews] objectAtIndex:0];  
        id nextResponder = [frontView nextResponder];  
        
        if ([nextResponder isKindOfClass:[UIViewController class]])  
            result = nextResponder;  
        else  
            result = window.rootViewController;  
        
        return result;  
    }  
    

    相关文章

      网友评论

          本文标题:iOS获取当前显示的UIViewController

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