如何在 Swift 中以编程方式更改设备方向?

Qui*_*tus 4 orientation ios swift

在我的应用程序中,我想更改设备方向。

我已经像在另一个相同主题的问题中一样尝试过:

let value = UIInterfaceOrientation.landscapeRight.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
Run Code Online (Sandbox Code Playgroud)

但这似乎只有在已经允许方向的情况下才有效,以便用户可以通过旋转设备来更改它,并且它还可以通过动画更改方向。但我希望我的应用程序在 VC1 中只有一个方向,而在 VC2 中只有一个方向。用户不应该影响方向,也不应该有动画。这可能吗?

对不起,我的英语不好....

jnb*_*ard 11

对于每个 VC 声明这个变量w/所需的方向。这是人像用的。

override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait }   
Run Code Online (Sandbox Code Playgroud)

然后在外观上强制执行所需的方向。

override func viewDidAppear(_ animated: Bool) {
  super.viewDidAppear(animated)
  UIView.setAnimationsEnabled(false)
  UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
  UIView.setAnimationsEnabled(true)
}
Run Code Online (Sandbox Code Playgroud)