Iphone – How to programmatically determine iPhone interface orientation

cocoa-touchiphone

The possible values for UIDevice.orientation include UIDeviceOrientationFaceUp and UIDeviceOrientationFaceDown. While it might be useful to know that the device is flat, this doesn't tell us whether it's flat displaying an interface oriented in portrait or landscape mode. Is there a way to find the current orientation of the GUI in cases where the device is returning ambiguous information? I suppose I could track orientation change events to remember the last portrait/landscape orientation or check the main UIView's bounds height and width, but that seems kludgey. Is there a property on the device or UIView that I'm missing?

Best Answer

You can get orientation by 3 ways:

  1. UIInterfaceOrientation orientation = 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.

  2. UIInterfaceOrientation orientation = [[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 this is the most effective way to retrieve real interface orientation.

  3. UIDeviceOrientation 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.