項目中有個頁面需要強制橫屏,代碼邏輯實現(xiàn)如下。
首先,創(chuàng)建一個UINavigationController的子類CustomNavigationController,重載
shouldAutorotate,
supportedInterfaceOrientations,
preferredInterfaceOrientationForPresentation 三個方法
/**
*
* @return 是否支持旋轉(zhuǎn)
*/
override var shouldAutorotate : Bool {
return viewControllers.last!.shouldAutorotate
}
/**
* 適配旋轉(zhuǎn)的類型
*
* @return 類型
*/
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return viewControllers.last!.supportedInterfaceOrientations
}
override var preferredInterfaceOrientationForPresentation : UIInterfaceOrientation {
return viewControllers.last!.preferredInterfaceOrientationForPresentation
}
然后,在AppDelegate中設(shè)置rootViewController
func setTheRootViewController() {
let mainTabBarController = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "mainTabBarController") as! MainTabBarController
let navigationController = CustomNavigationViewController(rootViewController: mainTabBarController)
navigationController.navigationBar.isTranslucent = false
window?.rootViewController = navigationController
}
之后,在基類BaseViewController里設(shè)置(假如沒有基類,A 推到 B,在A里面寫)
override var shouldAutorotate : Bool {
return false
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
override var preferredInterfaceOrientationForPresentation : UIInterfaceOrientation {
return UIInterfaceOrientation.portrait
}
最后,在將要橫屏的頁面假如如下代碼
override var shouldAutorotate : Bool {
return true
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.landscapeRight
}
override var preferredInterfaceOrientationForPresentation : UIInterfaceOrientation {
return UIInterfaceOrientation.landscapeRight
}
但是,在測試過程中,發(fā)現(xiàn)iPhone 6s Plus 在桌面狀態(tài)支持橫屏了,那么就引起了橫屏啟動的問題。按上面代碼實現(xiàn)之后,橫屏啟動時候界面是不轉(zhuǎn)為橫屏了,但是因為設(shè)備的 width 和 height 變了,所以整個界面的的width和height也跟著變了,但是方向沒變,界面就亂了。
我的window.rootViewController 是 NavigationController, 然后在
AppDelegate的didFinishLaunchingWithOptions launchOptions:里這樣寫
application.statusBarOrientation = .portrait
CustomNavigationController里面也需要添加
UIApplication.shared.setStatusBarOrientation(.portrait, animated: false)
然后在需要橫屏的頁面里面
UIApplication.shared.setStatusBarOrientation(.landscapeRight, animated: false)
這樣才實現(xiàn)了最終效果。而且進入橫屏頁面然后再推出原界面也不會出現(xiàn)橫屏的問題。
因為一直都是用的swift開發(fā),所以上面都是swift語法,OC只要自己轉(zhuǎn)一下即可。