最近做項目遇到一個需求晌端,就是大部分頁面都是豎屏,只有兩個頁面是橫屏恬砂,這就要用到強制旋轉(zhuǎn)屏幕了斩松。我查了網(wǎng)上的資料,人云亦云者眾多觉既,但是真正有效的很少惧盹,所以干脆我自己總結(jié)一個吧,demo見底部瞪讼,文章里所有代碼和設(shè)置都是demo里的钧椰。
第一步:設(shè)置項目屬性為只允許豎屏
需要注意的是,iPad需要在info.plist里設(shè)置:
第二步:AppDelegate里的代碼
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var isForceLandscape: Bool = false
var isForcePortrait: Bool = false
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow.init(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.rootViewController = UINavigationController.init(rootViewController: ViewController.init())
window?.makeKeyAndVisible()
return true
}
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if (isForceLandscape) {
//這里設(shè)置允許橫屏的類型
return .landscapeRight;
}else if (isForcePortrait){
return .portrait;
}
return .portrait;
}
}
第三步:在控制器里的代碼符欠,demo是寫在控制器的基類BaseViewController里的
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
///強制橫屏
func forceOrientationLandscape() {
let appdelegate = UIApplication.shared.delegate as! AppDelegate
appdelegate.isForceLandscape = true
appdelegate.isForcePortrait = false
appdelegate.application(UIApplication.shared, supportedInterfaceOrientationsFor: self.view.window)
//強制翻轉(zhuǎn)屏幕嫡霞,Home鍵在右邊。
UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
//刷新
UIViewController.attemptRotationToDeviceOrientation()
}
///強制豎屏
func forceOrientationPortrait() {
let appdelegate = UIApplication.shared.delegate as! AppDelegate
appdelegate.isForceLandscape = false
appdelegate.isForcePortrait = true
appdelegate.application(UIApplication.shared, supportedInterfaceOrientationsFor: self.view.window)
//強制翻轉(zhuǎn)屏幕希柿,Home鍵在右邊诊沪。
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
//刷新
UIViewController.attemptRotationToDeviceOrientation()
}
}
第四步:使用,demo里是TestViewController 使用橫屏曾撤,ViewController 使用豎屏:
在 TestViewController里使用強制橫屏:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 強制橫屏
forceOrientationLandscape()
}
在 ViewController里使用強制豎屏:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 強制豎屏
forceOrientationPortrait()
}