您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 關於 App 支援的螢幕方向設定

編輯:iOS 開發綜合

設定支援的螢幕方向有兩個層級:App 層級與 ViewController 層級,兩者存在約束關係,理解這層關係才能避免方向設定失效或崩潰。

App 層級設定

在 [Target] → [General] → [Device Orientation] 中勾選,如下圖:

預設情況下 Upside Down 沒有勾選,其餘四個方向都已勾選。

為什麼不建議勾選 Upside Down?因為 iPhone 的電話 App 並不支援倒置。若你的 App 支援 Upside Down,使用者正倒置握持時來電,就會看到整個來電畫面上下顛倒,體驗非常糟糕。一向講究使用者體驗的蘋果因此不建議開啟。

ViewController 層級設定

這裡有一點必須注意:ViewController 的設定受 App 層級約束,能設定的方向必須是 App 層級已勾選的其中之一。也就是說,若 App 層級沒勾 Upside Down,任何 ViewController 都無法啟用它。

iOS 6 以前的寫法:

// 只支援豎向
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

從 iOS 6 開始,上述方法已被捨棄,改為以下三個:

// 是否支援旋轉
- (BOOL)shouldAutorotate {
    return NO;
}

// 支援的方向
- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationPortrait;
}

// 畫面初次載入時的優先方向
// - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
//     return UIInterfaceOrientationPortrait;
// }

若專案仍需相容 iOS 6 之前的版本,被捨棄的那個方法也要一併保留。

iOS 8.3 的崩潰陷阱

從 iOS 8.3 開始,在含有 UIAlertView 的 ViewController 中彈出提示框時可能崩潰,Log 如下:

Terminating app due to uncaught exception 'UIApplicationInvalidInterfaceOrientation',
reason: 'Supported orientations has no common orientation with the application,
and [_UIAlertShimPresentingViewController shouldAutorotate] is returning YES'

查閱官方文件後可以發現,supportedInterfaceOrientations 的回傳值型別其實是 UIInterfaceOrientationMask,因此應該使用:

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

UIInterfaceOrientationMask 型別從 iOS 6 就已存在,只是直到 iOS 8.3 才會因為型別不匹配而崩潰——系統在計算「App 支援方向」與「ViewController 支援方向」的交集時,若拿到的值不在 Mask 列舉範圍內,交集為空就拋出例外。

至於 preferredInterfaceOrientationForPresentation,它的回傳值仍是舊的 UIInterfaceOrientation 型別,不需要改。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved