Search code examples
iosnibuiinterfaceorientationuiapplicationdelegate

rootViewController set but comes up as incorrect orientation


My situation is very similar to this question . I have an app that is universal where iPhone is in portrait orientation and the iPad is in Landscape and I switch between all of my main screens using the appDelegate.window.rootViewController = newScreen; The iPhone app works perfectly. The iPad app will sometime throw the screen up in portrait orientation instead of landscape. Here is some sample transition code:

AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
            ViewController* v = nil;
            if (IS_IPAD()) {
                v = [[ViewController alloc] initWithNibName:@"ViewController-iPad" bundle:nil];
            }else{
                v = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
            }
            [appDelegate.window setRootViewController:(UIViewController*)v];

I also tried this from this other question :

AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
            ViewController* v = nil;
            if (IS_IPAD()) {
                v = [[ViewController alloc] initWithNibName:@"ViewController-iPad" bundle:nil];
            }else{
                v = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
            }

            [UIView
             transitionWithView:appDelegate.window 
             duration:0.5
             options:UIViewAnimationOptionTransitionCrossDissolve
             animations:^(void) {
                 BOOL oldState = [UIView areAnimationsEnabled];
                 [UIView setAnimationsEnabled:NO];
                 [appDelegate.window setRootViewController:(UIViewController*)v];
                 [UIView setAnimationsEnabled:oldState];
             } 
             completion:nil];

But nothing has fixed it.

Also tried using [appDelegate.window makeKeyAndVisable] and [appDelegate.window makeKeyWindow] in the hopes that this would "shock" it into doing the correct orientation.


Solution

  • I've got it!

    Here's what my transition block looks like. The key thing I did was copy the transform (the thing that does the actual rotation) from the CALayer. Note that you'll have to include the Quartz framework and #import <QuartzCore/QuartzCore.h> at the top of your file.

    [UIView transitionWithView:self.window 
                      duration:0.5 
                       options:UIViewAnimationOptionTransitionCrossDissolve 
                    animations:^{                        
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        target.view.layer.transform = window.rootViewController.view.layer.transform;
        window.rootViewController = target;
        [UIView setAnimationsEnabled:oldState];
    } completion:nil];