Find an iPhone’s current orientation

Apr 5, 2010   #cocoa touch,  #objective-c  #tutorial 

While working on some code that changes a subview’s height/width based on the iPhone orientation, I discovered that if the user rotates the phone while on the navigation controller, the image view controller that gets pushed onto the navigation stack does not change its orientation to match.

I assumed incorrectly that whenever a parent’s willAnimateRotationToInterfaceOrientation:duration: is called, the subview’s would also be called. My first working thought was to store a UIInterfaceOrientation reference in my image view controller and whenever the willAnimate… method is called, it would set the reference. This worked fine, but felt very hacky.

It took me a little bit of Google searching, but you can get the current orientation at any time by calling the UIDevice class. Here’s a snippet of the code from my image view controller:

 1 - (void)viewDidAppear:(BOOL)animated {
 2  	[self setScrollSize];
 3  	[super viewDidAppear:animated];
 4  }
 5  - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
 6  	[self setScrollSize];
 7  } 
 8  - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
 9  	return (toInterfaceOrientation == UIInterfaceOrientationPortrait
10  || toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft
11  || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight);
12  } 
13  - (void)setScrollSize {
14  	UIInterfaceOrientation iOrientation = [[UIDevice currentDevice] orientation];
15  	if (iOrientation == UIInterfaceOrientationLandscapeLeft || iOrientation == UIInterfaceOrientationLandscapeRight) { 
16 		//Do something 
17 	} else { 
18 		//Do something else 
19 	}
20  }

The magic happens in the setScrollSize method, specifically in line 15. Here, I get the orientation from the currentDevice object. I then call this method whenever the view appears or whenever it is rotated. Between these two methods, I always set the correct orientation of my subview.

It’s very simple once you know how to implement it.