Orientation Detection at Runtime in iPad or iPhone

XCode If you support your iPad or iPhone application in both portrait or landscape mode, then orientation detection is essential for UI update. There are different ways to detect orientation personally I found the following solution is working best for my apps supporting iOS version >= 5.1

First declare the following 2 properties

@property (readwrite, assign) BOOL isShowingLandscapeView;
@property (readwrite, assign) BOOL previousOrientation;

Define the following 2 methods.

#pragma Notification
- (void) registerAllNotification{
    self.isShowingLandscapeView = UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation);
    self.previousOrientation    = NO;

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self

#pragma mark -
#pragma mark Orientation Method
- (void)orientationChanged:(NSNotification *)notification
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    if (UIDeviceOrientationIsLandscape(deviceOrientation) &&
        self.isShowingLandscapeView = YES;
    else if (UIDeviceOrientationIsPortrait(deviceOrientation) &&
        self.isShowingLandscapeView = NO;

    if (self.previousOrientation != self.isShowingLandscapeView){
        if (self.isShowingLandscapeView){
            NSLog(@"Orientation Change Occur: Landscape Mode");
        else {
            NSLog(@"Orientation Change Occur: Portrait Mode");

        [[NSNotificationCenter defaultCenter] postNotificationName:@"OrientationChange" object:nil];
        [self updateUI];

    self.previousOrientation = self.isShowingLandscapeView;

You must have to call [registerAllNotification] method in your viewDidLoad or ViewDidAppear method to register the event. And you have to define updateUI method where you can write the code to update UI based on orientation. So to know the current orientation just apply the logic

if (self.isShowingLandscapeView){
   //do the landscape tasks
else {
  //do the portrait tasks

I defined this code in my mainviewcontroller that has a reference in my delegate. So from other view controller I can easily access to know the current orientation. Also a notification send triggered when orientation change occurred, so from other view controller I can know this by registering an observer of the event. Here updateUI is a method defined in the other view controller.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUI) name:@"OrientationChange" object:nil];

mahmud ahsan

Computer programmer and hobbyist photographer from Bangladesh, lives in Malaysia. My [Business | Twitter | Linkedin | Instagram | Flickr | 500px]

You may also like