Detecting iOS UIDevice orientation

Try doing the following when the application loads or when your view loads:

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

Then add the following method:

- (void) orientationChanged:(NSNotification *)note
{
   UIDevice * device = note.object;
   switch(device.orientation)
   {
       case UIDeviceOrientationPortrait:
       /* start special animation */
       break;

       case UIDeviceOrientationPortraitUpsideDown:
       /* start special animation */
       break;

       default:
       break;
   };
}

The above will allow you to register for orientation changes of the device without enabling the autorotate of your view.


Note

In all cases in iOS, when you add an observor, also remove it at appropriate times (possibly, but not always, when the view appears/disappears). You can only have “pairs” of observe/unobserve code. If you do not do this the app will crash. Choosing where to observe/unobserve is beyond the scope of this QA. However you must have an “unobserve” to match the “observe” code above.

Leave a Comment