iOS获取当前显示的UIViewController

2016-03-08  本文已影响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;  
}  
上一篇下一篇

猜你喜欢

热点阅读