iosswiftswift2orientationuiinterfaceorientation

In Swift, how to get the device orientation correctly right after it's launched?


I use following code to see if the device is in landscape mode or not:

UIDevice.currentDevice().orientation.isLandscape.boolValue

It works BUT if I put my device in landscape mode before the app is launched, and after viewDidLoad, I call this line of code, it always returns false.

If I use this instead:

interfaceOrientation.isLandscape

it returns true, which is correct, but the compiler is showing a warning that interfaceOrientation was deprecated in iOS 8.0.

What is the correct way to get the device orientation right after the app is launched?


Solution

  • I have tested many times about orientation, so I have summed up some experience.

    In all iPhone devices, except iPhone6(s) plus, the only interface orientation is .portrait. If App is launched in landscape mode, there must be a change of orientation. One will receive the UIDeviceOrientationDidChangeNotification. It's an appropriate time to get the orientation.

    Regarding the launching when in landscape with iPhone6, the orientation after the launch will change once: enter image description here

    The launching when in landscape with iPhone6 plus, after launch the orientation never changed: enter image description here

    Two different screenshot with the same app, enter image description here

    So before the app does change orientation, the orientation is still like in the home page.

    In viewDidLoad, the orientation has not changed yet, the log will be the wrong direction.