Question

I'm adding a UIView to a UIWindow that's not the keyWindow. I'd like the UIView to rotate when the device rotates. Any special properties on the window or the view I need to set? Currently the view is not rotating.

I'm aware of the fact that only the first subview of the application's keyWindow is told about device rotations. As a test I added my view to the first subview of the keyWindow. This causes the view to rotate. However the view being a subview of the keyWindow's first subview won't work for various aesthetic reasons.

An alternative approach is observing device orientation changes in the view and writing the rotation code myself. However I'd like to avoid writing this code if possible (having an additional window is cleaner in my opinion).

Was it helpful?

Solution

UIView doesn't handle rotations, UIViewController does. So, all you need is to create a UIViewController, which implements shouldAutorotateToInterfaceOrientation and sets this controller as a rootViewController to your UIWindow

Something like that:

    UIViewController * vc = [[[MyViewController alloc] init] autorelease];

    vc.view.frame = [[UIScreen mainScreen] bounds];
    vc.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];

    //you vc.view initialization here

    UIWindow * window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    window.windowLevel = UIWindowLevelStatusBar;
    window.backgroundColor = [UIColor clearColor];
    [window setRootViewController:vc];
    [window makeKeyAndVisible];

and I used this MyViewController, cause I want it to reflect changes of main application

    @interface MyViewController : UIViewController

    @end

    @implementation MyViewController

    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
    {
        UIWindow *window = ((UIWindow *)[[UIApplication sharedApplication].windows objectAtIndex:0]);
        UIViewController *controller = window.rootViewController;

        if (!controller) {
            NSLog(@"%@", @"I would like to get rootViewController of main window");
            return YES;
        }
        return [controller shouldAutorotateToInterfaceOrientation:toInterfaceOrientation];
    }
    @end

but you can always just return YES for any orientation or write your logic, if you wish.

OTHER TIPS

You can add below code to your project

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didRotate:) name:UIDeviceOrientationDidChangeNotification object:nil];

and created the function to handle it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top