問題引言:
當Window界面上已彈出AlertView時,再用當前Window Present其他控制器,會導致界面卡死不動,Xcode 日誌顯示“ios Warning: Attempt to present < a viewController: 0x10d0611b0> on < UITabBarController: 0x101575b60> which is already presenting < UIAlertController: 0x10d11c2b0> ”
問題代碼:
UIWindow *fK = [[UIApplication sharedApplication] keyWindow];
[fK.rootViewController presentViewController:[UIViewController new] animated:YES completion:nil];
修正代碼:
UIWindow *fK = [[UIApplication sharedApplication] keyWindow];
//如果window已有彈出的視圖,會導致界面無法彈出,頁面卡死,這裏需要先把視圖關閉,再彈出
if (fK.rootViewController.presentedViewController != nil) {
[fK.rootViewController dismissViewControllerAnimated:NO completion:nil];
}
[fK.rootViewController presentViewController:[UIViewController new] animated:YES completion:nil];
根本問題解疑
有些人就會說:“爲什麼我一直present AlertController 就不會導致卡死呢?”
因爲系統在彈出alert時,單獨創建了一個新的window,同時我們的keyWindow也會指向這個window。
而我們自己寫present時並不會創建一個新的window,且系統不允許同時彈出多個視圖控制器,否則就會出現以上bug問題。
注:以上爲小弟的陋見,若表述解答錯誤,還希望您能在評論處指出,萬分感謝!