加速計是整個 iOS 螢幕旋轉的基礎,唯有依靠它,裝置才能判斷自己目前的姿態。iOS 定義了七種裝置方向:
typedef NS_ENUM(NSInteger, UIDeviceOrientation) {
UIDeviceOrientationUnknown,
UIDeviceOrientationPortrait, // 縱向,home 鍵在下
UIDeviceOrientationPortraitUpsideDown, // 縱向倒置,home 鍵在上
UIDeviceOrientationLandscapeLeft, // 橫向,home 鍵在右
UIDeviceOrientationLandscapeRight, // 橫向,home 鍵在左
UIDeviceOrientationFaceUp, // 平放,正面朝上
UIDeviceOrientationFaceDown // 平放,正面朝下
};
而介面方向只有四種,並與裝置方向做對應:
typedef NS_ENUM(NSInteger, UIInterfaceOrientation) {
UIInterfaceOrientationPortrait = UIDeviceOrientationPortrait,
UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
UIInterfaceOrientationLandscapeLeft = UIDeviceOrientationLandscapeRight,
UIInterfaceOrientationLandscapeRight = UIDeviceOrientationLandscapeLeft
};
注意 Landscape 左右是交叉對應的,這經常是新手混淆的來源。
加速計偵測到方向變化時,會發出 UIDeviceOrientationDidChangeNotification。任何關心方向的 view 都可以註冊這個通知並做出回應。UIKit 內部的處理順序是:
當 view controller 收到 window 傳來的方向變化,流程如下:
willRotateToInterfaceOrientation:duration:。若此 VC 是 container view controller,會繼續往下呼叫 content view controller 的對應方法。這裡適合先把某些 view 暫時隱藏。viewWillLayoutSubviews。此時 self.interfaceOrientation 與 statusBarOrientation 仍是原本的方向。willAnimateRotationToInterfaceOrientation:duration:,系統會把此方法內進行的屬性變化都包進 animation block。didRotateFromInterfaceOrientation:,通知旋轉動畫已完成。此時可把第 2 步隱藏的 view 顯示回來。
照著這個節奏處理,就能完整支援螢幕旋轉。
注意事項:view controller 隱藏時,裝置方向仍可能變化。例如 A 模態呈現全螢幕的 B 之後,A 完全不可見,因此收不到旋轉訊息;這時若旋轉了裝置,關掉 B 之後 A 的方向就會是錯的。解法是在 A 的 viewWillAppear 中更新方向。
實作建議:
iTouch、iPhone、iPad 都支援旋轉。要設定 App 支援哪些方向,通常在 Info.plist 中調整 Supported interface orientations;每個 view controller 也各自有方法可進一步收緊:
- (NSUInteger)supportedInterfaceOrientations; // iOS 6.0 及以後
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation; // iOS 6.0 之前
透過這些方法可以做到更細粒度的控制,例如只允許特定頁面旋轉。
那麼,旋轉時系統到底做了什麼?做個簡單實驗,在旋轉完成後印出 view 資訊:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
NSLog(@"did rotated to new Orientation, view Information %@", self.view);
}

Transform(變換矩陣)是一個 3×3 的矩陣:

透過它,可以對座標系統做縮放、平移、旋轉以及這些操作的任意組合。矩陣乘法不具交換律,操作順序不同結果就不同。UIView 有 transform 屬性,設定它即可改變該 view 在 superView 中的大小與姿態。

設 (x, y) 為原座標系中的位置,(x', y') 為變換後的位置,展開矩陣公式後可清楚看出關係:
CGAffineTransformIdentity。
把這些變換綜合起來,就能完成所有二維矩陣運算。
回頭對照前面的輸出:處於 Portrait 時矩陣為單位矩陣,因此沒有特別變化;轉到 UIInterfaceOrientationLandscapeLeft 時,設備順時針轉了 90°(逆時針為正、順時針為負),矩陣應為 (cos−90°, sin−90°, −sin−90°, cos−90°, tx, ty),未做平移故 tx、ty 皆為 0,正好與主控台印出的 transform = [0, -1, 1, 0, 0, 0] 吻合。其他兩個方向的結果也與推導一致。
結論很清楚:螢幕旋轉的本質就是 view 的矩陣變換。設備偵測到旋轉後通知程式,程式再通知 window,window 通知它的 rootViewController,rootViewController 設定自己 view 的 transform,旋轉就此完成。
如果直接把某個 view 加到 window 上,系統不會代勞旋轉,這時就得自行設定 transform。這種情形雖然不常見,但確實存在——例如許多 App 用來做狀態列訊息提示的自建 window,就是靠自行設定 transform 來支援旋轉的。