Skip to content

Instantly share code, notes, and snippets.

@tsycho
Created April 26, 2013 20:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tsycho/5470389 to your computer and use it in GitHub Desktop.
Save tsycho/5470389 to your computer and use it in GitHub Desktop.
Manual rotation and transformation of a view. Useful when a view needs to be displayed without knowing which view controller it will be a part of, eg: status/error notifications that will come on top of all other views.
- (void)reposition {
// https://developer.apple.com/library/ios/#qa/qa2010/qa1688.html
// tl;dr Only the first subview in the window receives orientation changes.
// So we apply a transform manually to rotate the view, and change the origin of the frame so
// that it remains in a top-center position for the user.
UIInterfaceOrientation orientation =
[UIApplication sharedApplication].statusBarOrientation;
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
CGAffineTransform viewTransform = CGAffineTransformIdentity;
CGFloat xPosition = ceilf((keyWindow.frame.size.width - kOverlaySize.width) / 2.0);
CGFloat yPosition = kTopMargin;
CGRect frame = CGRectZero;
CGFloat windowWidth = keyWindow.frame.size.width;
CGFloat windowHeight = keyWindow.frame.size.height;
switch (orientation) {
case UIInterfaceOrientationPortrait:
frame = CGRectMake(xPosition, yPosition, kOverlaySize.width, kOverlaySize.height);
break;
case UIInterfaceOrientationPortraitUpsideDown:
// Rotate the view 180 degrees, and position on bottomY-centerX of original screen.
viewTransform = CGAffineTransformMakeRotation(M_PI);
yPosition = windowHeight - kTopMargin - kOverlaySize.height;
frame = CGRectMake(xPosition, yPosition, kOverlaySize.width, kOverlaySize.height);
break;
case UIInterfaceOrientationLandscapeLeft: // Home button is on the left
// Rotate view by -90 degrees, and position on leftX-centerY of original screen.
viewTransform = CGAffineTransformMakeRotation(-M_PI_2);
xPosition = kTopMargin;
yPosition = ceilf((windowHeight - kOverlaySize.width) / 2.0);
frame = CGRectMake(xPosition, yPosition, kOverlaySize.height, kOverlaySize.width);
break;
case UIInterfaceOrientationLandscapeRight: // Home button is on the right
// Rotate view by 90 degrees, and position on rightX-centerY of original screen.
viewTransform = CGAffineTransformMakeRotation(M_PI_2);
xPosition = windowWidth - kTopMargin - kOverlaySize.height;
yPosition = ceilf((windowHeight - kOverlaySize.width) / 2.0);
frame = CGRectMake(xPosition, yPosition, kOverlaySize.height, kOverlaySize.width);
break;
default:
[self hide];
}
self.transform = viewTransform;
self.frame = frame;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment