简体   繁体   English

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

[英]How to change Device Orientation programmatically in Swift?

In my app I want to change the device orientation.在我的应用程序中,我想更改设备方向。

I`ve tried it like in the other question with the same topic:我已经像在另一个相同主题的问题中一样尝试过:

let value = UIInterfaceOrientation.landscapeRight.rawValue
UIDevice.current.setValue(value, forKey: "orientation")

But this seems only to work if the orientation is already allowed so that the user can change it with rotating the device, and it also change the orientation with an animation.但这似乎只有在已经允许方向的情况下才有效,以便用户可以通过旋转设备来更改它,并且它还可以通过动画更改方向。 But I want my app to only have one orientation in VC1 and to have only one orientation in VC2.但我希望我的应用程序在 VC1 中只有一个方向,而在 VC2 中只有一个方向。 The user should not have influence on the Orientation, and there should no animation.用户不应该影响方向,也不应该有动画。 Is this possible?这可能吗?

Sorry for my bad english....对不起,我的英语不好....

For each VC declare this variable w/ desired orientation.对于每个 VC 声明这个变量w/所需的方向。 This is for portrait.这是人像用的。

override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait }   

Then on appearance enforce the desired orientation.然后在外观上强制执行所需的方向。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM