1. 程式人生 > >iOS 獲取當前window

iOS 獲取當前window

在iOS 開發過程中,我們對頁面進行操作的時候,經常會獲取當前控制器controller或者檢視view的window。下面給大家分享一個方法

/**
 獲取當前的window,不一定是keywindow

 @return 當前window
 */
-(UIWindow*)mainWindow{
    id appDelegate = [UIApplication sharedApplication].delegate;
    if (appDelegate && [appDelegate respondsToSelector:@selector(window)]) {
        return [appDelegate window];
    }
    
    
    NSArray *windows = [UIApplication sharedApplication].windows;
    if ([windows count] == 1) {
        return [windows firstObject];
    } else {
        for (UIWindow *window in windows) {
            if (window.windowLevel == UIWindowLevelNormal) {
                return window;
            }
        }
    }
    
    return nil;
}

搞定!