iOS 关于屏幕强制旋转的方法

参考链接:iOS屏幕旋

  1. 首先选择支持的旋转方向(两种方法,推荐第二种)
    (1)修改Info.plist文件,见图1
1.png

(2)直接上图,(勾选即可)

iOS 关于屏幕强制旋转的方法_第1张图片
2.png

2.在AppDelegate中添加属性方法
在.h中添加一个属性allowRotation

@interface AppDelegate : UIResponder 

@property (strong, nonatomic) UIWindow *window;

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

@end

.m中添加下面的方法

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window{
    if (_allowRotation == YES) {
        return UIInterfaceOrientationMaskLandscapeRight;
    }else{
        return (UIInterfaceOrientationMaskPortrait);
    }
}

3.在你需要旋转的控制器.m中添加一下方法

- (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.点击旋转按钮调用- (void)setNewOrientation:(BOOL)fullscreen方法

//横竖屏切换按钮方法
-(void)screen{
    //记着#import "AppDelegate.h"
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
   
    if (_fullScreen ) {//横屏情况下,点击此按钮变为竖屏
        appDelegate.allowRotation = NO;//设置竖屏
        [self setNewOrientation:NO];//调用转屏代码
        self.navigationController.navigationBar.hidden = NO;//navbar消失
        [self setViewFrame:NO];//竖屏布局
    }else{//竖屏情况下,点击此按钮变为横屏
        appDelegate.allowRotation = YES;////设置横屏
        [self setNewOrientation:YES];////调用转屏代码
        self.navigationController.navigationBar.hidden = YES;//navbar出现
        [self setViewFrame:YES];//横屏布局
    }
}

你可能感兴趣的:(iOS 关于屏幕强制旋转的方法)