多數 App 只跑豎屏,但影片播放、遊戲、圖表頁面往往需要橫屏。iOS 控制方向的方式是在視圖控制器中覆寫 supportedInterfaceOrientations,回傳一個 UIInterfaceOrientationMask 位掩碼。
一個實務上很常見的做法,是在 UINavigationController 的子類中統一管控整個導航棧的方向:
#import "LKNavigationController.h"
@interface LKNavigationController ()
@end
@implementation LKNavigationController
#pragma mark - 控制當前控制器支援哪些方向
/**
* 回傳值為 UIInterfaceOrientationMask
*/
- (NSUInteger)supportedInterfaceOrientations {
/**
* UIInterfaceOrientationMaskPortrait 豎屏(正常)
* UIInterfaceOrientationMaskPortraitUpsideDown 豎屏(上下顛倒)
* UIInterfaceOrientationMaskLandscapeLeft 橫屏向左
* UIInterfaceOrientationMaskLandscapeRight 橫屏向右
* UIInterfaceOrientationMaskLandscape 橫屏(左 + 右)
* UIInterfaceOrientationMaskAll 全部方向
* UIInterfaceOrientationMaskAllButUpsideDown 全部但排除顛倒
*/
return UIInterfaceOrientationMaskPortrait;
}
@end
1. 三個方法要一起看。 除了 supportedInterfaceOrientations,還有 shouldAutorotate(回傳 YES 才允許自動旋轉)與 preferredInterfaceOrientationForPresentation(指定以哪個方向啟動)。三者缺一,方向鎖定常常不生效。
2. 容器控制器會攔截詢問。 UINavigationController 與 UITabBarController 預設會以自己的實作回應,子控制器回傳的方向會被忽略。解法就是像上面這樣覆寫容器類,並在需要時把詢問轉發給 topViewController:
- (NSUInteger)supportedInterfaceOrientations {
return self.topViewController.supportedInterfaceOrientations;
}
- (BOOL)shouldAutorotate {
return YES;
}
3. 記得同步專案配置。 AppDelegate 實作的方向方法、Info.plist 的「Supported interface orientations」以及這裡的回傳值必須一致,否則會出現「代碼允許但實際不轉」的情況。
4. 強制旋轉。 若要跳轉到某頁時強制轉屏,可用 UIDevice 的 setOrientation:(私有 API,不建議上線)或 iOS 16 之後提供的 setNeedsUpdateOfSupportedInterfaceOrientations 搭配 requestGeometryUpdate 公開 API。