Easiest way to support multiple orientations? How do I load a custom NIB when the application is in Landscape?

Peter Hajas picture Peter Hajas · Mar 23, 2010 · Viewed 33.2k times · Source

I have an application in which I would like to support multiple orientations. I have two .xib files that I want to use, myViewController.xib and myViewControllerLandscape.xib. myViewController.xib exists in project/Resources and myViewControllerLandscape.xib exists in the root project directory.

What I want to do is use a separate NIB (myViewControllerLandscape.xib) for my rotations. I try detecting rotation in viewDidLoad like this:

if((self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (self.interfaceOrientation == UIInterfaceOrientationLandscapeRight))
 {
  NSLog(@"Landscape detected!");
  [self initWithNibName:@"myViewControllerLandscape" bundle:nil];

 }

But I can see in gdb that this isn't executed when the app is started with the device in landscape. The NSLog message doesn't fire. Why is this? What have I done wrong?

Also, if I explicitly put the initWithNibName function call in the viewDidLoad method, that nib is not loaded, and it continues with the myViewController.xib file. What's wrong with my call? Should I specify a bundle?

Thanks!

Answer

Adam picture Adam · May 10, 2012

I found a much better way that works independent of the nav controller. Right now, I have this working when embedded in a nav controller, and when NOT embedded (although I'm not using the nav controller right now, so there may be some bug I've not seen - e.g. the PUSH transition animation might go funny, or something)

Two NIBs, using Apple's naming convention. I suspect that in iOS 6 or 7, Apple might add this as a "feature". I'm using it in my apps and it works perfectly:

  1. triggers on WILL rotate, not SHOULD rotate (waits until the rotate anim is about to start)
  2. uses the Apple naming convention for landscape/portrait files (Default.png is Default-landscape.png if you want Apple to auto-load a landscape version)
  3. reloads the new NIB
  4. which resets the self.view - this will AUTOMATICALLY update the display
  5. and then it calls viewDidLoad (Apple will NOT call this for you, if you manually reload a NIB)
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if( UIInterfaceOrientationIsLandscape(toInterfaceOrientation) )
    {
        [[NSBundle mainBundle] loadNibNamed: [NSString stringWithFormat:@"%@-landscape", NSStringFromClass([self class])]
                                      owner: self
                                    options: nil];
        [self viewDidLoad];
    }
    else
    {
        [[NSBundle mainBundle] loadNibNamed: [NSString stringWithFormat:@"%@", NSStringFromClass([self class])]
                                      owner: self
                                    options: nil];
        [self viewDidLoad];
    }
}