简体   繁体   中英

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. 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. 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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