在要橫屏的控制器下面設置:
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下面聲明一個靜態(tài)變量族扰,添加代理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
}
}
}