Search code examples
iosuiwindowuiscreen

Autorotate issues with second UIScreen on iOS8.0 (and 8.1)


My app drives a second screen (external monitor) but I'm seeing some 'odd' things with regards to rotation (things that don't happen on iOS7)

If I launch the app (and connect the second screen) in landscape orientation then hit the home button to put the app into the background, then reopen the app then the second screen (attached to the monitor) is rotated through 90 degress and only uses half the screen. No amount of subsequent rotating fixes this.

I'm pretty confident this is a bug - but I'd be happy to know otherwise. Below is the code to reproduce it in a simple single view application.

Thanks

@interface AppDelegate ()

@property (nonatomic, strong) UIWindow* externalWindow;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(screenDidConnect:) name:UIScreenDidConnectNotification object:nil];

    UIScreen* externalScreen = ([UIScreen screens].count > 1 ? [[UIScreen screens] objectAtIndex:1] : nil);
    if (externalScreen)
    {
        [self setupExternalScreen:externalScreen];
    }

    return YES;
}

- (void) screenDidConnect:(NSNotification *)aNotification
{
    UIScreen* externalScreen = (UIScreen*)aNotification.object;
    [self setupExternalScreen:externalScreen];
}

- (void)setupExternalScreen:(UIScreen*)externalScreen
{
    externalScreen.currentMode = externalScreen.preferredMode;

    self.externalWindow = [[UIWindow alloc] initWithFrame:externalScreen.bounds];
    self.externalWindow.screen = externalScreen;
    self.externalWindow.clipsToBounds = YES;
    self.externalWindow.hidden = NO;
    [self.externalWindow makeKeyAndVisible];

    UIViewController* externalViewController = [[UIViewController alloc] initWithNibName:nil bundle:nil];
    externalViewController.view.backgroundColor = [UIColor redColor];
    self.externalWindow.rootViewController = externalViewController;
}
@end

Solution

  • OK - fixed it.

    Rather than set the

    self.externalWindow.rootViewController = externalViewController;
    

    Instead, just add the view as a subView of the window (remembering to keep a reference on the view controller object)

    self.externalViewController.view.frame = self.externalWindow.frame;
    [self.externalWindow addSubview:self.externalViewController.view];
    

    I guess the view controller stuff was getting confused.....