iOS --- 理解UIWindow及其常见使用场景

来源:互联网 发布:手机注册淘宝达人 编辑:程序博客网 时间:2024/05/16 15:26

UIWindow继承自UIView, 用来管理和协调各种视图. 提供一个区域来显示视图, 将事件event分发给视图.
每个iOS应用必须包含一个window用于展示APP的交互页面. 且一个APP通常只有一个UIWindow, 包含了APP的可视内容.
即使有多个, 也只有一个UIWindow可以接收用户的touch事件.

The two principal functions of a window are to provide an area for displaying its views and to distribute events to the views

所以, UIWindow的主要作用有两个:
1. 提供一个显示view的区域.
2. 将事件分发给view(如touch事件, 横竖屏的变化等)

keyWindow

The key window is the one that is designated to receive keyboard and other non-touch related events. Only one window at a time may be the key window.

通常在AppDelegate中的didFinishLaunchingWithOptions方法中, 执行如下代码设置keyWindow:

let story = UIStoryboard(name: "Main", bundle: nil)let rootViewController: RootViewController = story.instantiateViewControllerWithIdentifier("RootViewController")let navigationController = UINavigationController(rootViewController: rootViewController)let window = UIWindow(frame: UIScreen.mainScreen().bounds)window.rootViewController = navigationControllerwindow.makeKeyAndVisible() // 调用makeKeyAndVisible使该窗口为keyWindow并可见

获取keyWindow的方式:

UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;UIViewController *rootViewController = keyWindow.rootViewController;

windowLevel

UIWindow有一个windowLevel属性, 表示屏幕上的显示优先级, 通常会有三个值, 优先级顺序为:
UIWindowLevelAlert > UIWindowLevelStatusBar > UIWindowLevelNormal.

例如, 当有Alert出现的时候, 其他地方都点不了, 说明其优先级最高. 而状态栏次之.
通过这样,也可以设置某些显示的优先级(是alert还是statusBar)。

使用场景

UIWindow的使用场景:
如有道云笔记的密码保护功能. 当用户从任何界面按Home键退出, 然后过一会儿再从后台切换回来, 显示一个密码输入界面.
因该密码输入界面可能从任何界面弹出, 且要覆盖在所有界面的最上层, 所以使用UIWindow比较合适.

使用时, 通过makeKeyAndVisible和resignKeyWindow两个方法来控制keyWindow.
简单的Demo请参考:
DemoKeyWindow

0 0