Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 506
Jace999 Avatar asked Feb 03 '12 00:02

Jace999


People also ask

How do you check orientation on iPhone?

Swipe down from the top-right corner of your screen to open Control Center. Tap the Portrait Orientation Lock button to make sure that it's off. Turn your iPhone sideways.

How can we detect the orientation of the screen?

You can detect this change in orientation on Android as well as iOS with the following code: var supportsOrientationChange = "onorientationchange" in window, orientationEvent = supportsOrientationChange ?


1 Answers

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.

like image 145
David M. Syzdek Avatar answered Sep 30 '22 03:09

David M. Syzdek