How to change Device Orientation programmatically in Swift?

冷暖自知 提交于 2020-04-15 08:37:42

问题


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. The user should not have influence on the Orientation, and there should no animation. Is this possible?

Sorry for my bad english....


回答1:


For each VC declare this variable w/ desired orientation. 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)
  }


来源:https://stackoverflow.com/questions/50936519/how-to-change-device-orientation-programmatically-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!