UIWindow 是一種特殊的 UIView,在一個 App 中通常只有一個。iOS 程式啟動後建立的第一個視圖物件就是 UIWindow,接著建立控制器的 view,最後把它掛到 UIWindow 上,畫面才會真正顯示。
換句話說,一個 iOS App 之所以能被看見,完全是因為有 UIWindow;沒有它,任何 UI 都無處安放。
[UIApplication sharedApplication].windows:本 App 開啟的所有 UIWindow 列表,能藉此取得其中任何一個 view。平時輸入文字時彈出的鍵盤,其實就住在一個全新的 UIWindow 裡。[UIApplication sharedApplication].keyWindow:應用程式的主視窗,同一時刻只會有一個。view.window:取得某個 UIView 所處的 UIWindow。補充一點:經驗證,非 keyWindow 其實也能接收鍵盤訊息。因此若某個 UIWindow 內的文字欄位無法輸入,keyWindow 並不一定是根因,仍值得作為排查方向之一。
UIWindow 有三個層級:Normal、StatusBar、Alert,對應值分別是 0、1000、2000。也就是說 Normal 最低、StatusBar 居中、Alert 最高。
一般程式的介面處於 Normal 層;系統頂部狀態列屬於 StatusBar 層;UIActionSheet 與 UIAlertView 這類用於中斷流程、提醒使用者的元件,則落在 Alert 層。顯示時遵循層級優先原則:層級高的蓋在上層,低的在下層。
官方文件的說法是:keyWindow 是被指定用來接收鍵盤以及其他非觸控類事件的視窗,且同一時刻只能有一個視窗擔任此角色。
觀察 UIWindow 的文件,會發現四個與視窗狀態變動有關的通知:
UIWindowDidBecomeVisibleNotification
UIWindowDidBecomeHiddenNotification
UIWindowDidBecomeKeyNotification
UIWindowDidResignKeyNotification
這些通知的 object 就是發生變化的 window 本身,userInfo 則為空。註冊之後印出訊息,就能清楚觀察 keyWindow 的交接與視窗的顯示/隱藏過程。典型流程是:
iOS 7 之前,UIWindow 的 bounds 不會隨設備方向改變;從 iOS 8 開始,當裝置旋轉時,window.bounds.size.width 與 height 也會跟著互換。
寫個簡單的測試即可驗證,在 delegate 中註冊方向變更通知:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(orientationChanged:)
name:UIDeviceOrientationDidChangeNotification
object:nil];
return YES;
}
- (void)orientationChanged:(NSNotification *)noti {
UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
NSString *orientationDes = nil;
switch (orientation) {
case UIDeviceOrientationLandscapeLeft:
orientationDes = @"UIInterfaceOrientationLandscapeRight"; break;
case UIDeviceOrientationLandscapeRight:
orientationDes = @"UIInterfaceOrientationLandscapeLeft"; break;
case UIDeviceOrientationPortrait:
orientationDes = @"UIInterfaceOrientationPortrait"; break;
case UIDeviceOrientationPortraitUpsideDown:
orientationDes = @"UIInterfaceOrientationPortraitUpsideDown"; break;
default:
orientationDes = @""; break;
}
NSLog(@"system ver: %@, orientaion: %@, window bounds: %@",
[UIDevice currentDevice].systemVersion,
orientationDes,
NSStringFromCGRect(self.window.bounds));
}
在 iOS 8 上執行,會看到 bounds 隨著方向互換:
orientaion: UIInterfaceOrientationLandscapeRight, window bounds: {{0, 0}, {320, 480}}
orientaion: UIInterfaceOrientationPortrait, window bounds: {{0, 0}, {480, 320}}
orientaion: UIInterfaceOrientationLandscapeLeft, window bounds: {{0, 0}, {320, 480}}
orientaion: UIInterfaceOrientationPortraitUpsideDown, window bounds: {{0, 0}, {480, 320}}
而在 iOS 7 及更早版本上,無論怎麼轉,window bounds 都固定是 {{0, 0}, {320, 480}}。
對比之下很清楚:iOS 8 調整了 UIWindow 處理旋轉的策略。這項變更可能讓既有專案的版面出現問題,但新行為其實更貼近直覺——縱向時 width < height,橫向時 width > height,符合所見即所得。
題外話:不論 iOS 7 還是 iOS 8,所有 ViewController 的 bounds 都是正確的。因此只要堅持一個原則——「所有版面都基於 VC.view.bounds 佈局」,App 的顯示就不會出錯。