Jace999 Jace999 - 8 months ago 43
iOS Question

Detecting IOS UIDevice orientation

I need to detect when the device is in portrait orientation so that I can fire off a special animation. But I do not want my view to autorotate.

How do I override a view autorotating when the device is rotated to portrait? My app only needs to display it's view in landscape but it seems I need to support portrait also if I want to be able to detect a rotation to portrait.


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

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

Then add the following method:

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

       case UIDeviceOrientationPortraitUpsideDown:
       /* start special animation */


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


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.