Difference between UIApplication.shared.keyWindow and AppDelegate.window

1. UIApplication.shared.keyWindow
     documentation explains:
    This property holds the  UIWindow object in the  windows array that is most recently sent the  makeKeyAndVisible message.
    This property holds the UIWindow object in the windows array, which recently sent the makeKeyAndVisible message.
    So when getting the rootViewController, you need to pay attention.
2. If we have not manually set the AppDelegate.window
    window, then it is the default window at the beginning of the program. If it has been manually set, it will always be the window set for us until we manually set it. Change.

There is a situation: when using UIAlertView, when the item is clicked, the proxy is triggered

    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
       
        //(UIApplication.shared.delegate as? AppDelegate) 不等于 UIApplication.shared.keyWindow
        //而且两个window的rootVC也不一样
        
        //会失败
        //UIApplication.shared.keyWindow?.rootViewController?.present(ViewController1(), animated: true, completion: nil)
        
        //成功
        (UIApplication.shared.delegate as? AppDelegate)?.window?.rootViewController?.present(ViewController1(), animated: true, completion: nil)
    }

UIAlertView will add a window to it and become the keywindow (which is called internally makeKeyAndVisible)
and will not disappear until the proxy func alertView(_ alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) is executed.
Therefore, you need to pay attention when getting rootVC.

Another point of attention: the same ViewController cannot present multiple VCs at the same time, you need to pay attention when using rootVC to present

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325021507&siteId=291194637