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时需要注意

转载于:https://my.oschina.net/dahuilang123/blog/1802699

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值