Different ways of getting current interface orientation?

IosOrientation

Ios Problem Overview


There're 3 ways to get current interface orientation that I know of:

  • self.interfaceOrientation
  • [[UIApplication sharedApplication] statusBarOrientation]
  • [[UIDevice currentDevice] orientation]

What are the differences among them?

Ios Solutions


Solution 1 - Ios

self.interfaceOrientation returns UIInterfaceOrientation, current orientation of the interface. It is a property in UIViewController, you can access to this one only in UIViewController classes.

[[UIApplication sharedApplication] statusBarOrientation] returns UIInterfaceOrientation, current orientation of the application's status bar. You can access to that property in any point of your application. My experience shows that it's more effective way to retrieve real interface orientation.

[[UIDevice currentDevice] orientation] returns UIDeviceOrientation, device orientation. You can access to that property in any point of your application. But note that UIDeviceOrientation is not always UIInterfaceOrientation. For example, when your device is on a plain table you can receive unexpected value.

Solution 2 - Ios

[[UIApplication sharedApplication] statusBarOrientation] - it always equals to one of four values: portrait, landscape left, landscape right and portrait upside down.

[[UIDevice currentDevice] orientation] - this one equals to standart four values and also: unknown, face up or face down.

[[UIApplication sharedApplication] statusBarOrientation] - is more prefered way to get interface orientation.

Solution 3 - Ios

Since iOS 13

You can use the interfaceOrientation property of the window scene

UIWindow.windowScene.interfaceOrientation

let interfaceOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation ?? UIInterfaceOrientation.unknown

Solution 4 - Ios

All view controllers have this function

   override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
          //fromInterfaceOrientation.isLandscape
   }

or you can user the status bar orientation

   if UIApplication.sharedApplication().statusBarOrientation == UIInterfaceOrientation.Portrait {
        //
   }

Works in iOS 9 :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnhView Question on Stackoverflow
Solution 1 - IosberylliumView Answer on Stackoverflow
Solution 2 - IosholodnyalexView Answer on Stackoverflow
Solution 3 - IosПаша МатюхинView Answer on Stackoverflow
Solution 4 - IosEduardo IriasView Answer on Stackoverflow