欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS-[UIApplication sharedApplication].keyWindow

程序员文章站 2024-01-14 22:47:52
...

前言:在日常开发中经常碰到这样的需求,弹出一个和系统风格不一样的自定义弹窗,一般情况下会使用[UIApplication sharedApplication].keyWindow[UIApplication sharedApplication].delegate.window去添加需要的自定义弹窗,这样做的好处是,可以覆盖整个屏幕(如果使用View添加,frame会乱),简单直接,那这俩者究竟有什么区别。

[UIApplication sharedApplication].keyWindow

先来看看苹果官方对keyWindow的定义:

This property holds the UIWindow object in the windows array that is 
most recently sent the makeKeyAndVisible message.

最近发送makeKeyAndVisible消息的UIWindow就是该属性。 那makeKeyAndVisible有什么作用,大概意思是,使发送该消息UIWindow成为主键,并且可见,继续看官方定义:

This is a convenience method to show the current window and position 
it in front of all other windows at the same level or lower. If you only 
want to show the window, change its `hidden` property to `NO`.

展示当前Window并将它移动到所有Windows的最上层的便利方法,如果只想展示这个Window,将其Hidden属性设置为NO

当在windowrootViewController的时候,有时候keyWindow会为空,只要将makeKeyAndVisible的实现在rootViewController初始化之前就没有问题了。

[UIApplication sharedApplication].delegate.window
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.rootViewController = [ViewController new];
    _window.backgroundColor = [UIColor whiteColor];
    [_window makeKeyAndVisible];
}

这个.delegate.window就是_window,可以得出[UIApplication sharedApplication].keyWindow[UIApplication sharedApplication].delegate.window是一样的

注意**
*** 1 如果在之后想要自定义UIWindow必须要设置[UIApplication sharedApplication].delegate.window 为想要设置的window
*** 2 如果弹框有跳转到其他app的,最好使用[UIApplication sharedApplication].delegate.window,否则有可能会出现UI错位