Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone - UIWindow rotating depending on current orientation?

I am adding an additional UIWindow to my app. My main window rotates correctly, but this additional window I have added does not rotate.

What is the best way to rotate a UIWindow according to the current device orientation?

like image 806
aryaxt Avatar asked Jul 14 '11 17:07

aryaxt


2 Answers

You need to roll your own for UIWindow.

Listen for UIApplicationDidChangeStatusBarFrameNotification notifications, and then set the the transform when the status bar changes.

You can read the current orientation from -[UIApplication statusBarOrientation], and calculate the transform like this:

#define DegreesToRadians(degrees) (degrees * M_PI / 180)  - (CGAffineTransform)transformForOrientation:(UIInterfaceOrientation)orientation {      switch (orientation) {          case UIInterfaceOrientationLandscapeLeft:             return CGAffineTransformMakeRotation(-DegreesToRadians(90));          case UIInterfaceOrientationLandscapeRight:             return CGAffineTransformMakeRotation(DegreesToRadians(90));          case UIInterfaceOrientationPortraitUpsideDown:             return CGAffineTransformMakeRotation(DegreesToRadians(180));          case UIInterfaceOrientationPortrait:         default:             return CGAffineTransformMakeRotation(DegreesToRadians(0));     } }  - (void)statusBarDidChangeFrame:(NSNotification *)notification {      UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];      [self setTransform:[self transformForOrientation:orientation]];  } 

Depending on your window´s size you might need to update the frame as well.

like image 57
Morten Fast Avatar answered Oct 02 '22 20:10

Morten Fast


Just create a UIViewController with its own UIView, assign it as rootViewController to your window and add all further UI to the view of the controller (not directly to the window) and the controller will take care of all rotations for you:

UIApplication * app = [UIApplication sharedApplication]; UIWindow * appWindow = app.delegate.window;  UIWindow * newWindow = [[UIWindow alloc] initWithFrame:appWindow.frame]; UIView * newView = [[UIView alloc] initWithFrame:appWindow.frame]; UIViewController * viewctrl = [[UIViewController alloc] init];  viewctrl.view = newView; newWindow.rootViewController = viewctrl;  // Now add all your UI elements to newView, not newWindow. // viewctrl takes care of all device rotations for you.  [newWindow makeKeyAndVisible]; // Or just newWindow.hidden = NO if it shall not become key 

Of course, exactly the same setup can also be created in interface builder w/o a single line of code (except for setting frame sizes to fill the whole screen before displaying the window).

like image 27
Mecki Avatar answered Oct 02 '22 20:10

Mecki