螢幕上顯示的每個視圖都被包含於UIWindow對象,app內每個window之間相互獨立。app接收到的事件都最先路由到合適的window對象,再由此派發到合適的視圖。需要注意的是,keyWindow接收鍵盤事件和其他與觸摸無關的事件。
Windows與ViewControllers一起協作,從而實現旋轉螢幕變換,完成各項任務。避免直接調用- [UIWindow addSubview:]方法來添加視圖,而是通過操作UIViewController來添加視圖,從而實現旋轉螢幕自適應。
螢幕上的window根據是否是keyWindow,可分成兩種: keyWindow:app必需,且同時間只會有一個。
例子:
UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];window.rootViewController = [[UIViewController alloc] init];[window makeKeyAndVisible];/** keep strong reference to window */
其他輔助window:用於顯示alert/statusBar等輔助視圖。
例子:
UIWindow *window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 64)];window.windowLevel = UIWindowLevelStatusBar + 1;/** keep strong reference to window */CustomViewController *vc = [[CustomViewController alloc] init];/** CustomViewController could rewite shouldAutorotate & supportedInterfaceOrientations to support orientations */window.rootViewController = vc;window.hidden = NO; /** must have to show */