Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I detect the orientation of the device on iOS?

I have a question on how to detect the device orientation on iOS. I don't need to receive change notifications, just the current orientation itself. This seems to be a rather simple question, but I haven't been able to wrap my head around it. Below is what I have done so far:

UIDevice *myDevice = [UIDevice currentDevice] ; [myDevice beginGeneratingDeviceOrientationNotifications]; UIDeviceOrientation deviceOrientation = myDevice.orientation; BOOL isCurrentlyLandscapeView = UIDeviceOrientationIsLandscape(deviceOrientation); [myDevice endGeneratingDeviceOrientationNotifications]; 

In my mind this should work. I enable the device to receive device orientation notices, then ask for what orientation it is in, but then it is not working and I don't know why.

like image 292
JusmanX Avatar asked Apr 05 '11 23:04

JusmanX


2 Answers

Really old thread, but no real solution.

I Had the same problem, but found out that getting The UIDeviceOrientation isn't always consistent, so instead use this:

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;  if(orientation == 0) //Default orientation      //UI is in Default (Portrait) -- this is really a just a failsafe.  else if(orientation == UIInterfaceOrientationPortrait)     //Do something if the orientation is in Portrait else if(orientation == UIInterfaceOrientationLandscapeLeft)     // Do something if Left else if(orientation == UIInterfaceOrientationLandscapeRight)     //Do something if right 
like image 147
Moe Avatar answered Oct 07 '22 16:10

Moe


if UIViewController:

if (UIDeviceOrientationIsLandscape(self.interfaceOrientation)) {     //  } 

if UIView:

if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {     // } 

UIDevice.h:

#define UIDeviceOrientationIsPortrait(orientation)  ((orientation) == UIDeviceOrientationPortrait || (orientation) == UIDeviceOrientationPortraitUpsideDown) #define UIDeviceOrientationIsLandscape(orientation) ((orientation) == UIDeviceOrientationLandscapeLeft || (orientation) == UIDeviceOrientationLandscapeRight) 

Updated:

add this code to xxx-Prefix.pch then you can use it anywhere:

// check device orientation #define dDeviceOrientation [[UIDevice currentDevice] orientation] #define isPortrait  UIDeviceOrientationIsPortrait(dDeviceOrientation) #define isLandscape UIDeviceOrientationIsLandscape(dDeviceOrientation) #define isFaceUp    dDeviceOrientation == UIDeviceOrientationFaceUp   ? YES : NO #define isFaceDown  dDeviceOrientation == UIDeviceOrientationFaceDown ? YES : NO 

usage:

if (isLandscape) { NSLog(@"Landscape"); } 
like image 45
TONy.W Avatar answered Oct 07 '22 15:10

TONy.W