iOS 单个界面旋转屏幕

1 创建UIDevice的category

#import 

NS_ASSUME_NONNULL_BEGIN

@interface UIDevice (Orientation)

/**
 * @interfaceOrientation 输入要强制转屏的方向
 */
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation;

@end

NS_ASSUME_NONNULL_END

@implementation UIDevice (Orientation)

+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation{
        
        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
        
        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
        
        //NSNumber *orientationTarget = [NSNumber numberWithInt:interfaceOrientation];
        
        [[UIDevice currentDevice] setValue:@(interfaceOrientation) forKey:@"orientation"];
    
}

@end

2 AppDelegate里面设置屏幕旋转权限

#pragma mark:旋转屏幕
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window{
    if (self.allowRotation == YES) {
        //横屏
        return UIInterfaceOrientationMaskLandscape;      
    }else{
        //竖屏
        return UIInterfaceOrientationMaskPortrait;
    }
}

3 目标界面ViewDidLoad方法里面添加:

        appDelegate.allowRotation = YES;
        //调用横屏代码
        [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];

3.1 在出现界面和消失界面的方法里面设置禁用手势返回代码

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
        //禁用侧滑手势方法  
     self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //开启侧滑手势方法
 self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

3.2 退出界面的时候

        appDelegate.allowRotation = NO;//关闭横屏仅允许竖屏
        //切换到竖屏
        [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
         //present进来的
        [self.navigationController popViewControllerAnimated:YES];
        //push进来的
        [self dismissViewControllerAnimated:true completion:^{
        //
    }]  

你可能感兴趣的:(iOS 单个界面旋转屏幕)