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

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 = navigationController
window.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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值