如何从纵向模式转换到横向模式并locking它?

我有一个电影视图压缩在肖像模式的右下方视口。 当用户展开电影视图时,电影视图将以横向模式展开为全屏。 无论设备是什么方向,我也想在全屏时将电影视图locking到横向模式。

注意:我所有的其他视图都是以肖像模式。

我用这个代码来引用这个post ,

应用设置,

在这里输入图像说明

AppDelegate.swift

internal var shouldRotate = false func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { return shouldRotate ? .allButUpsideDown : .portrait } 

视图控制器,

 func expandPlayerWindow(button: UIButton) { self.player.view.frame = CGRect(x:0, y:-20, width: UIScreen.main.bounds.maxY, height: UIScreen.main.bounds.maxX) let appDelegate = UIApplication.shared.delegate as! AppDelegate print(appDelegate.shouldRotate) print(self.supportedInterfaceOrientations) appDelegate.shouldRotate = true // or false to disable rotation let value = UIInterfaceOrientation.landscapeLeft.rawValue UIDevice.current.setValue(value, forKey: "orientation") print(appDelegate.shouldRotate) print(self.supportedInterfaceOrientations) appDelegate.shouldRotate = false print(appDelegate.shouldRotate) print(self.supportedInterfaceOrientations) UIApplication.shared.isStatusBarHidden = false } 

日志,

 false UIInterfaceOrientationMask(rawValue: 26) true UIInterfaceOrientationMask(rawValue: 26) false UIInterfaceOrientationMask(rawValue: 26) 

在setorientation之前,我将shouldRotate设置为true,这使得视图可以转换为横向模式。 设置方向后,我将shoudRotate设置为false以禁用旋转。 然后我testing它,当我点击button,电影视图改变为风景,之后我旋转我的设备电影视图改变为肖像,并locking到肖像模式而不是风景模式。

这是由这个function引起的,

 func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { return shouldRotate ? .allButUpsideDown : .portrait } 

改变.allButUpsideDown.landscape将会做。

可行的代码,

AppDelegate.swift

 func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { return shouldRotate ? .landscape : .portrait } 

视图控制器,

 func expandPlayerWindow() { self.player.view.frame = CGRect(x:0, y:-20, width: UIScreen.main.bounds.maxY, height: UIScreen.main.bounds.maxX) let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.shouldRotate = true // or false to disable rotation let value = UIInterfaceOrientation.landscapeLeft.rawValue UIDevice.current.setValue(value, forKey: "orientation") appDelegate.shouldRotate = true UIApplication.shared.isStatusBarHidden = true }