在AppDelegate中:
1.添加属性:
var isForcedLandscape = false //标记是否横屏
2.重写代理方法:
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if self.isForcedLandscape {
return UIInterfaceOrientationMask.landscapeRight
}
return UIInterfaceOrientationMask.portrait
}
写两个全局方法:
func setHorizontalScreen() { //需要横屏时调用此方法
isForcedLandscape = true
let value = UIInterfaceOrientation.landscapeRight.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
func setVerticalScreen(){ //需要竖屏时调用此方法
isForcedLandscape = false
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}