UIDeviceOrientation programmatically switching between landscape and portrait

Hi,


Based on a condition, I forcefully display the view in portrait mode. For another condition, I want to display my app in landscape mode.

I get the device orientation using


let orientation = UIApplication.shared.statusBarOrientation

var orientationValue = UIInterfaceOrientation.landscapeRight.rawValue

if orientation == .landscapeLeft || orientation == .landscapeRight {

orientationValue = orientation.rawValue

}

UIDevice.current.setValue(orientationValue, forKey: "orientation")


What happens with this code is, after forcefully displaying portrait mode, the orientation becomes portrait and the orientationValue always remains landscape right as declared, even when the device is actually in landscape left orientation.

I tried setting boolean variables to force display landscape or not, but in all cases, the if condition becomes false after forcefully displaying portrait mode.


Any ways to get the device's actual orientation?

Replies

To test if landscape, I use


UIApplication.shared.statusBarOrientation.isLandscape


Could you try with this test ?


To set the orientation, try using:

setStatusBarOrientation(_:animated:)

However, this is deprecated.


Could look here:

https://developer.apple.com/documentation/uikit/uitraitcollection

It returns false, since I already forced the view to display in Portrait.


I missed mentioning it, my app's deployment target is 10.0

>UIDeviceOrientation


Devs are normally advised to avoid using device orientation checks. Unless you know you need to check device orientation specifically, I'd suggest to work w/UI orientation, instead, especially when using UI-centric code. Don't conflate the two or you risk debugging mixed signals.