iPhone iPad SDK | Get Device Orientation

25/03/2010


It may be useful to get the current orientation of the iPhone/iPad to then have custom code ran depending on the view.
A landscape and portrait UI are quite distinct and it would be common that orientation detection is used to perform tasks based upon the current orientation.


A quick way to get the current orientation is:

- (void)viewDidLoad {
[super viewDidLoad];

//The extra setup is not required for Portrait// if portrait set apprunning ==1
if(self.interfaceOrientation == UIInterfaceOrientationPortrait || self.interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@”apprunning”];
} else [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@”apprunning”];

Notice, this checks the orientation for UIInterfaceOrientationPortrait or UIInterfaceOrientationPortraitUpsideDown and then performs a task.

For reference, the Landscape Orientations are called: UIDeviceOrientationLandscapeLeft and UIDeviceOrientationLandscapeRight.

To add rotation support to a view controller, use the following method (this method is typically included already).

// Ensure that the view controller supports rotation and therefore show in both portrait and landscape.
– (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}

View Comments