ios屏幕旋转

目标:app只在个别界面支持屏幕的横向旋转,别的界面都是只能竖屏

1.首先勾选手机支持的旋转方向

2. AppDelegate.h中设置一个属性 

@property(nonatomic,assign)BOOL allowRotation;//是否允许在横向上旋转

AppDelegate.m中实现如下方法

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window{

    if (_allowRotation == YES) {  // 如果属性值为YES,则允许屏幕旋转

        return UIInterfaceOrientationMaskLandscape;  // 这里是屏幕要旋转的方向(只能在横屏方向旋转)

    }else{

        return (UIInterfaceOrientationMaskPortrait);//只能竖屏

    }

}

 3.在需要横向旋转的界面做一下设置

    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    appDelegate.allowRotation = YES;//(以上2行代码,可以理解为打开横屏开关)

    [self setNewOrientation:YES];//调用转屏代码(即一旦进入该界面就成为横屏)

#pragma mark--- 设置屏幕旋转

- (void)setNewOrientation:(BOOL)fullscreen

{

    if (fullscreen) {

        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];

        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];

        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];

        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];

    }else{

        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];

        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];

        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];

        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];

    }

}

4.在退出横屏界面是作如下设置

AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    appDelegate.allowRotation = NO;//关闭横屏仅允许竖屏

    [self setNewOrientation:NO];

- (void)setNewOrientation:(BOOL)fullscreen

{

    if (fullscreen) {

        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];

        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];

        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];

        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];

    }else{

        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];

        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];

        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];

        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];

    }

}

猜你喜欢

转载自blog.csdn.net/u013857988/article/details/84937520