In my iPhone app I have a view that I want to show only in portrait mode. When navigating to that view it should be automatically displayed in portrait view. When navigating away, the orientation should change back to what it was, or, if the device orientation has changed, adapt to that. I could find information on forcing an orientation and preventing auto-rotate. I could not find anything on how to change back to the correct orientation after navigating away from that view.
So my idea was to
- save the initial orientation (store in
currentOrientation
) - subscribe to orientation change event to keep track of orientation changes while the content is locked to portrait (update
currentOrientation
) - when leaving the view, restore the correct orientation using the
currentOrientation
value.
Edit (code now removed): Apart from it not working it was a dangerous way to go as it made extensive use of unsupported APIs.
Edit:
I believe this question can now be boiled down to the following:
Is there a documented, supported way to force the interface orientation independent of the device orientation?
setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation")
has been recommended many times on SO and elsewhere but it does indeed seem to be an unsupported hack.Is there a documented, supported way to update the interface orientation to the device orientation? That would be needed to "recover" from the forced interface orientation in another view without having to trigger auto rotation by turning the device back and forth.
Supported are supportedInterfaceOrientations()
and shouldAutorotate()
. But these will only lock the interfaceOrientation after the device has been turned to that position. They do not prevent wrong initial orientation.
There are many questions similar to this one, showing that this problem setting is not uncommon, but so far no satisfactory and complete solution using supported methods.
setValue(… forKey: "orientation")
bit because that is undocumented and supported. You should be able to achieve what you want usingsupportedInterfaceOrientations()
,shouldAutorotate()
, andattemptRotationToDeviceOrientation()
. – GehringsetValue()
is used to force the view to portrait when it's opened while the device is in landscape.supportedInterfaceOrientations()
andshouldAutoRotate()
did not take care of that. I needed to turn the device to portrait first, and then the view was locked to portrait. I found several references to thesetValue()
method, which, of course, does not make it good practice. How else can I achieve that? – Culdesac