在平時開發中,我們經常會忽略一個問題,就是當我們的App內有需要橫屏的頁面,而首頁只支持豎屏,在plus的設備上,桌面是運行橫屏的,此時進入App,首頁布局會出錯。在延伸一下這個問題,當我們開發一款支持iPad的App時,如何保證App在任何情況下進入首頁都保持豎屏狀態?
方法一、
我們可以這樣設置首頁的控制器:
// 必須兩個都是 .portrait才可以
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return .portrait
}
如果有UITabBarController,這樣設置:
// 必須兩個都是 .portrait才可以
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return selectedViewController?.supportedInterfaceOrientations ?? .portrait
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return selectedViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
}
如果有 UINavigationController,這樣設置:
// 必須兩個都是 .portrait才可以保證首頁一定是豎屏
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return topViewController?.supportedInterfaceOrientations ?? .portrait
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return topViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
}
方法二、
設置一個全局的變量
var isAllowLandscape: Bool = false
在AppDelegate中設置:
// 控制整個App所允許旋轉的方向
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return isAllowLandscape ? .allButUpsideDown : .portrait
}
在需要的時候改變 isAllowLandscape的值即可。