Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView subview of UIWindow doesn't rotate

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).

like image 418
SundayMonday Avatar asked Jan 05 '12 04:01

SundayMonday


1 Answers

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.

like image 127
Mark Pervovskiy Avatar answered Sep 29 '22 16:09

Mark Pervovskiy