1.Xcode工程配置中的Device Orientation 勾选Landscape Right,如图
2.在AppDelegate中添加方法关闭横竖屏切换
/// 是否允许转向
public static var isAllowRotation : Bool = false
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if AppDelegate.isAllowRotation == true {
return .landscapeRight
} else {
return .portrait
}
}
3.在需要强制横屏的控制器中,添加以下方法
3.1添加旋转为横屏或竖屏的方法
// MARK: true: 强制横屏 false: 竖屏
func setOrientationLandscapeRight(fullscreen : Bool) {
if fullscreen == true {
let resetOrientationTarget = NSNumber.init(value: UIInterfaceOrientation.unknown.rawValue)
UIDevice.current.setValue(resetOrientationTarget, forKey: "orientation")
let orientationTarget = NSNumber.init(value: UIInterfaceOrientation.landscapeRight.rawValue)
UIDevice.current.setValue(orientationTarget, forKey: "orientation")
} else {
let resetOrientationTarget = NSNumber.init(value: UIInterfaceOrientation.unknown.rawValue)
UIDevice.current.setValue(resetOrientationTarget, forKey: "orientation")
let orientationTarget = NSNumber.init(value: UIInterfaceOrientation.portrait.rawValue)
UIDevice.current.setValue(orientationTarget, forKey: "orientation")
}
}
3.2 viewDidLoad强制横屏
override func viewDidLoad() {
super.viewDidLoad()
AppDelegate.isAllowRotation = true
setOrientationLandscapeRight(fullscreen: true)
// 返回上一个界面,需要强制竖屏
setupBackAction(action: #selector(backAction))
}
3.3 返回上一个界面,强制竖屏
@objc func backAction() {
AppDelegate.isAllowRotation = false
setOrientationLandscapeRight(fullscreen: false)
self.popViewController(animated: true)
}
参考了Objective-C 版本