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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • UIView的功能 负责渲染区域的内容,并且响应该区域内发生的触摸事件 UIWindow 在iOS App中,UI...
    小蘑菇2阅读 821评论 4 5
  • 在iOS开发中经常会涉及到触摸事件。本想自己总结一下,但是遇到了这篇文章,感觉总结的已经很到位,特此转载。作者:L...
    WQ_UESTC阅读 6,225评论 4 26
  • 每一个IOS程序都有一个UIWindow,在我们通过模板简历工程的时候,xcode会自动帮我们生成一个window...
    jumping鹏阅读 1,173评论 0 0
  • UIWindow 简介 一个UIWindow对象为应用程序的用户界面提供了背景以及重要的事件处理行为。UIWind...
    ripperhe阅读 23,801评论 24 58
  • 今年制造业的状况不太好,很多小厂倒闭了,也有小老板卷着钱财跑路了。 我所在的是新能源行业,听上去好像发展前景很好,...
    艾羽勤阅读 213评论 4 2

友情链接更多精彩内容