如何将视图从纵向模式更改为横向模式并锁定?

how to change a view from portrait mode to landscape mode and lock it?

我在右下视口使用纵向模式压缩了一个电影视图。当用户展开电影视图时,电影视图将在横向模式下扩展到全屏。我还想在全屏时将电影视图锁定为横向模式,无论设备的方向如何。

注意:我所有的其他视图都是纵向模式。

我已经用这段代码引用了这个 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 以禁用旋转。然后我测试它,当我点击按钮时,电影视图变为横向,旋转我的设备后电影视图变为纵向,并锁定为纵向模式而不是横向模式。

是这个函数造成的,

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
}