從程式控制 view controller 畫面的方向
當 iOS App 在 iPhone / iPad 上執行時,它有直向和橫向兩種顯示模式,我們可從 General 頁面的 iPhone Orientation & iPad Orientation 設定。
不過有時我們想要分別控制畫面的方向,想讓某個畫面只支援直向,某個畫面只支援橫向,這有機會實現嗎 ?
當然沒問題,我們可在 view controller 裡定義 supportedInterfaceOrientations,控制 controller 畫面顯示的方向。
以下例子在 ViewController 裡定義 supportedInterfaceOrientations,回傳 landscape,因此 ViewController 的畫面將以橫向顯示,即使 Supported interface orientations 有設定 Portrait。
class ViewController: UIViewController {
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
.landscape
}
}
值得注意的,Supported interface orientations 設定的方向代表 App 具有支援此方向的能力,比方我們設定 Portrait,表示它可以直向,但在 controller 的程式裡我們可另外控制畫面只以橫向顯示。在 Supported interface orientations 沒設定的方向,則表示完全不支援,比方沒設定 landscape 時,就算 supportedInterfaceOrientations 回傳 landscape 也是不可能橫向的。
當 navigation controller 或 tab bar controller 控制畫面時
當 navigation controller 或 tab bar controller 控制畫面時,它們將決定畫面是否轉向,因此我們須自訂繼承 navigation controller 或 tab bar controller 的類別,在裡面定義 supportedInterfaceOrientations 設定 App 的方向。
接下來讓我們試試搭配 navigation controller 的例子。
當我們只在 ViewController 定義 supportedInterfaceOrientations 為橫向時,App 在 portrait 時將如下圖所示,它還是傻傻地以直向顯示。
問題出在此時控制方向的是 navigation controller。因此我們自訂繼承 UINavigationController 的 NavigationController,在裡面定義 supportedInterfaceOrientations 控制方向。我們希望由 navigation controller 目前顯示的 controller 控制方向,因此回傳 topViewController?.supportedInterfaceOrientations。
class NavigationController: UINavigationController {
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
topViewController?.supportedInterfaceOrientations ?? .all
}
Cool,App 在 portrait 時順利地以橫向的方法顯示。