views:

2454

answers:

2

I don't need to specify the orientation in this case, I just need to detect it, but I'm having trouble. I have conditional code that should only work in portrait, and if the device is in landscape I need to do something else. Since the deviceOrientation is not necessarily the same as the interfaceOrientation, I can't come up with a way to test for portrait mode.

Most tutorials I find on Google are ways to force landscape or do some sort of rotation. The only thing I want to do is just determine what the orientation is. Here is my code, which is not working:

-(void)viewDidLoad {
    [super viewDidLoad];
    //currentOrientation is declared as UIInterfaceOrientation currentOrientation
    currentOrientation = [[UIApplication sharedApplication] statusBarOrientation];
NSLog(@"%@",currentOrientation);  // == NULL
}

I need to determine the value of the interfaceOrientation and program conditionally. Thanks for your help!

+6  A: 

Are you aware of the interfaceOrientation property of the UIViewController class?

- (void) viewDidLoad {
    [super viewDidLoad];
    BOOL isPortrait = UIDeviceOrientationIsPortrait(self.interfaceOrientation);
    // now do whatever you need
}

Or are you after [[UIDevice currentDevice] orientation]?

zoul
Your answer helps tremendously. Now all I have to test for is if isPortrait is true, instead of trying to add orientation code into the viewController rotation methods
JustinXXVII
Be aware that this doesn't always seem to work. Particularly if your controller is the first in your application. In my simulator tests [self interfaceOrientation] always returns as 1. Maybe it's different on the actual device.. at the very least.. hard to test.
Jasconius
i believe when the app first start up, the default orientation is portrait. That might explain why [self interfaceOrientation] always returns 1.
Joo Park
@zoul, isPortrait bool value returning me "YES" in simulator. I have not iPad device, then how i detecting current device orientation in viewDidLoad?
RRB
this does not work on detailViewController inside a split view... isPortrait is always YES. Any ideas?
Artilheiro
+2  A: 

Especially at launch I have found the following to be always accurate for the UI, regardless of what the UIDevice says the orientation is.

[UIApplication sharedApplication].statusBarOrientation
slycrel
Thank you, I will give it a shot as well
JustinXXVII