最近项目需要展现一些图表,需要在用到的页面将页面设置为横屏,查阅整理出三个方案记录下来。其中方案一和方案二整个页面旋转,方案三只是view旋转,导航栏不会跟随旋转。
方案一:
- AppDelegate.h中设置
/*** 是否允许横屏的标记 */
@property (nonatomic, assign)BOOL allowRotation;
- AppDelegate.m中设置
#pragma mark - 页面方向支持
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (self.allowRotation) {
return UIInterfaceOrientationMaskLandscapeRight;
}
return UIInterfaceOrientationMaskPortrait;
}
- (void)setAllowRotation:(BOOL)allowRotation {
_allowRotation = allowRotation;
if([[UIDevice currentDevice]respondsToSelector:@selector(setOrientation:)]) {
SEL selector = NSSelectorFromString(@"setOrientation:");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:[UIDevice currentDevice]];
int val;
if (allowRotation) {
val = UIInterfaceOrientationLandscapeRight;//横屏
}else {
val = UIDeviceOrientationPortrait;//竖屏
}
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
}
- 在需要横屏的页面调用
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.allowRotation = YES;
- 离开页面调用
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; appDelegate.allowRotation = NO;
方案二:
- 在横屏页
+ (void)rotationScreen {
CGRect frame = [UIScreen mainScreen].bounds;
AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
app.window.transform = CGAffineTransformMakeRotation(M_PI * 0.5);
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:YES];
app.window.bounds = CGRectMake(0, 0, frame.size.height, frame.size.width);
}
- 离开页面
+ (void)recoverScreen {
CGRect frame = [UIScreen mainScreen].bounds;
AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
app.window.transform = CGAffineTransformIdentity;
app.window.bounds = CGRectMake(0, 0, frame.size.width, frame.size.height);
}
方案三:
- 在旋转页面
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:YES];
CGFloat duration = [UIApplication sharedApplication].statusBarOrientationAnimationDuration;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:duration];
//在这里设置view.transform需要匹配的旋转角度的大小就可以了。
self.view.transform = CGAffineTransformMakeRotation(M_PI/2);
[UIView commitAnimations];