iOS强制屏幕旋转

2017-11-29  本文已影响0人  林_城

最近项目需要展现一些图表,需要在用到的页面将页面设置为横屏,查阅整理出三个方案记录下来。其中方案一和方案二整个页面旋转,方案三只是view旋转,导航栏不会跟随旋转。

方案一:

/***  是否允许横屏的标记 */
@property (nonatomic, assign)BOOL allowRotation;
#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];
上一篇 下一篇

猜你喜欢

热点阅读