如何从纵向模式更改为横向模式并锁定它?

问题描述:

我有一个电影视图压缩在肖像模式的右下视口。当用户展开电影视图时,电影视图将以横向模式展开为全屏。无论设备是什么方向,我也想在全屏幕时将电影视图锁定到横向模式。如何从纵向模式更改为横向模式并锁定它?

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

我已经参考本post与此代码,

应用设置,

enter image description here

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以禁用旋转。然后我测试它,当我点击按钮时,电影视图改变为风景,在我旋转设备后,电影视图改变为肖像,并锁定到肖像模式而不是风景模式。

+0

怎么样的电影视图的父视图。你是否阻止他们旋转? –

+0

是的,我认为阻止它们不仅仅是电影视图。 –

+1

您的电影是否查看视图控制器的视图,以及视图控制器是否在每种模式下为shouldAutorotate和supportedInterfaceOrientations返回适当的值? –

它是由该功能引起的,

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 
}