Reputation: 10011
I have been trying to change the device orientation on a button click event for 2 days but I am not able to achieve it properly.
So, I have an iPhone app with a minimum version of 12.4, and the device that I am using to test is 14.4. I have used the code mentioned in this project here (which works properly when presenting a new view controller using push or present) but the same doesn't work when on the same view controller. The user needs to rotate his/her device to initiate the orientation change.
This is the code that I have in the view controller that I am trying to rotate on a button click event.
let appDelegate = AppDelegate.sharedInstance
let oldOrientaion = appDelegate.deviceOrientation
appDelegate.deviceOrientation = oldOrientaion == .landscapeRight ? .portrait : .landscapeRight
let value = appDelegate.deviceOrientation.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
Can someone please help me in figuring out what exactly is missing from this?
Also, on a side note, the view controller is presented on a different view controller so even if I try to present a new view controller like in the project for some time and change the orientation there it doesn't work.
Edit:
This is fixed now. I was trying to use the UIInterfaceOrientationMask
to set the orientation instead of UIInterfaceOrientation
. So changing the code to use UIInterfaceOrientation
at the end works properly now.
Thanks for the help.
Upvotes: 1
Views: 1032
Reputation: 2217
You are doing everything correctly, just need to call the attemptRotationToDeviceOrientation
method to the oration change to take effect. Based on the documentation:
Some view controllers may want to use app-specific conditions to determine what interface orientations are supported. If your view controller does this, when those conditions change, your app should call this class method. The system immediately attempts to rotate to the new orientation.
In your code it will look like:
UIViewController.attemptRotationToDeviceOrientation()
Upvotes: 2