UIView UIWindow mobility does not rotate

I am adding UIView to UIWindow , and not to keyWindow. I would like the UIView to UIView when the device is spinning. Any special properties on the window or view I need to set? Presentation does not rotate.

I know that only about the first time you view the keyWindow application is keyWindow talking about device turns. As a test, I added my view to the first keyWindow subzone. This rotates the view. However, the view, which is the approach to the first keyWindow , will not work for various aesthetic reasons.

An alternative approach is to observe changes in the orientation of the device in the representation and record the rotation code. However, I would like to avoid writing this code if possible (with my additional window cleaner).

+7
source share
2 answers

UIView does not handle rotations, UIViewController does. So, all you need to do is create a UIViewController that implements shouldAutorotateToInterfaceOrientation and sets this controller as rootViewController in 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 because I want it to reflect the changes in the 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 own logic if you want.

+7
source

You can add the code below to your project.

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

and created a function to handle it.

+2
source

All Articles