iPhone - UIWindow rotating depending on current orientation?
You need set new window's rootViewController.Then the window's subviews will rotate correctly.
myNewWindow!.rootViewController = self
Then you can change frames in the rotate methods.
e.g. (swift in ios8)
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
customAlertView.frame = UIScreen.mainScreen().bounds
}
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).
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.