iOS開發-獲取rootViewController的正確方式

獲取工程中window上面的RootViewController keyWindow是,在windows數組中最近時間調用makeKeyAndVisible方法的屬性。windows

方法一:建議使用

AppDelegate *app =(AppDelegate *) [UIApplication sharedApplication].delegate;
UIViewController *rootViewController1 = appdelegate.window.rootViewController;
複製代碼
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if ([appdelegate.window.rootViewController isKindOfClass:["xxxrootVC" class]] == YES) {
        // 這樣更保險
    }
複製代碼

方法二:不建議使用

UIAlertController或UIAlertView或UIActionSheet彈出後,keyWindow就會變成UIAlertControllerShimPresenterWindow這個類數組

UIWindow *window = [UIApplication sharedApplication].keyWindow;
UIViewController *rootViewController2 = window.rootViewController;
複製代碼

alertView的出現是由於,生成了一個新的window,加在了界面上面。 這個時候獲取到的keyWindow就是UIAlertControllerShimPresenterWindow。bash

相關文章
相關標籤/搜索