最近做项目遇到一个需求,就是大部分页面都是竖屏,只有两个页面是横屏,这就要用到强制旋转屏幕了。我查了网上的资料,人云亦云者众多,但是真正有效的很少,所以干脆我自己总结一个吧,demo见底部,文章里所有代码和设置都是demo里的。
第一步:设置项目属性为只允许竖屏
image.png
需要注意的是,iPad需要在info.plist里设置:
image.png
第二步: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) {
//这里设置允许横屏的类型
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)
//强制翻转屏幕,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)
//强制翻转屏幕,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()
}