UIApplication.shared.keyWindow和AppDelegate.window的区别

1、UIApplication.shared.keyWindow
     文档解释:
    This property holds the UIWindow object in the windows array that is most recently sent the makeKeyAndVisible message.
    该属性保存windows数组中的UIWindow对象,该对象最近发送了makeKeyAndVisible消息。
    所以当获取rootViewController时,需要注意,
2、AppDelegate.window
    该window如果我们没有手动设置过,那么就是程序一开始默认的window,如果手动设置过,就会是一直为我们设置的window,直到我们人为改变。

有一种情况:使用UIAlertView 时,当点击item时,触发代理

    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 会添加一个window上去,成为keywindow(内部调用了makeKeyAndVisible
等到执行代理func alertView(_ alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int)时才会消失。
所以获取rootVC时需要注意

另外注意点:同一个ViewController不能同时present多个VC,用rootVC present时需要注意

猜你喜欢

转载自my.oschina.net/dahuilang123/blog/1802699