在要横屏的控制器下面设置:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
AppDelegate.isLandscape = true
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//将试图还原为竖屏
AppDelegate.isLandscape = false
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
在AppDelegate下面声明一个静态变量,添加代理UIApplicationDelegate的方法
class AppDelegate: UIResponder {
static var isLandscape:Bool = false
}
extension AppDelegate:UIApplicationDelegate {
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if AppDelegate.isLandscape {
return UIInterfaceOrientationMask.landscapeLeft
}else{
return UIInterfaceOrientationMask.portrait
}
}
}