1

How to get the current orientation of iPhone? I surfed this site, and found two methods as followings.

  • [UIApplication sharedApplication].statusBarOrientation;
  • [[UIDevice currentDevice] orientation];

Which one is the right way to get the current orientation ? I tried two methods under simulator 4.1, but there are some problems for both methods.

AechoLiu
  • 17,522
  • 9
  • 100
  • 118

2 Answers2

6

Register your class to listen to UIDeviceOrientationDidChangeNotification then handle the device orientation accordingly.

[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(deviceRotated:)
name:UIDeviceOrientationDidChangeNotification
object:[UIDevice currentDevice]];

and handle the device's orientation properly:

- (void)deviceRotated: (id) sender{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    if (orientation == UIDeviceOrientationFaceUp ||
        orientation == UIDeviceOrientationFaceDown)
    {
        //Device rotated up/down
    }

    if (orientation == UIDeviceOrientationPortraitUpsideDown)
    {
    }
    else if (orientation == UIDeviceOrientationLandscapeLeft)
    {
    }
    else if (orientation == UIDeviceOrientationLandscapeRight)
    {
    }
}
Hoang Pham
  • 6,899
  • 11
  • 57
  • 70
  • Thank you for help. I vote up because one answer for one question. The way works well, and thank you. – AechoLiu Oct 01 '10 at 02:51
3

[[UIDevice currentDevice] orientation] gets the current physical orientation of the device. [UIApplication sharedApplication].statusBarOrientation gets the orientation of the UI. If the app ever returns NO to the shouldAutorotateToInterfaceOrientation: method, the two values will not be the same.

grahamparks
  • 16,130
  • 5
  • 49
  • 43
  • Thank you for showing me a clear picture about those two methods. – AechoLiu Oct 01 '10 at 02:50
  • Something to note: If you have the device on a flat surface, `[[UIDevice currentDevice] orientation]` may not return the value you want. I had an interface I dynamically layout based on user input that went wonky on me when I used that. Using the `statusBarOrientation` seems to be working great. – Michael Kernahan Nov 10 '10 at 21:39