1
votes

I need to get the interface orientation in the viewWillAppear method of my UIViewController. What I did is:

if (self.interfaceOrientation == UIInterfaceOrientationPortrait)
   NSLog(@"Portrait");
else
   NSLog(@"Landscape");

When in landscape, I'm always getting Portrait in the viewWillAppear and Landscape in the viewDidAppear. Why?

So, I tried using [[UIApplication sharedApplication] statusBarOrientation], but the same happens. I also tried another solution posted here in Stack Overflow:

UIDevice* device = [UIDevice currentDevice];
[device beginGeneratingDeviceOrientationNotifications];
UIDeviceOrientation currentOrientation = device.orientation;
[device endGeneratingDeviceOrientationNotifications];

This seems to correctly return the orientation, but now I'm left with the problem of mapping UIDeviceOrientation to UIInterfaceOrientation, which is not possible as far as I know (face up and face down cannot be mapped).

Any solution to this issue?

2
If you can support iOS 5+ it's better to do this work in the -viewWillLayoutSubviews method. If your app has just finished loading, -viewWillAppear may be called before the views frame is set and the window has finished orienting itself. If you need that info in iOS 4 you really need to wait for -viewDidAppear to be called. - Jason Coco
If you're using a navigation controller, what about checking self.navigationController.interfaceOrientation in viewWillAppear? - Anton
@JasonCoco That is working perfectly for me. It would be interesting to find a solution for iOS4 as well but that is good. - Luca Carlon
@AntonHolmquist Tried that as well, forgot to mention. I'm still getting always portrait. Aren't you? - Luca Carlon
@JasonCoco If you answer to the question with the information you provided in the comment, I'll mark that as accepted. That is the only working option provided so far. - Luca Carlon

2 Answers

0
votes

Use [UIApplication sharedApplication].statusBarOrientation instead.

if([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait || [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown) {
    // Portrait
}
if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeLeft || [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight){
    // Landscape
}
0
votes

The first comment by JasonCoco is the best solution I found to this issue.