iOS 界面强制横屏

场景

present系统横屏三个方法在iOS16上失效

App内部嵌套小游戏需要横屏,嵌套容器在SDK中

项目tager设置方向为仅允许竖屏
0.png

场景应用方案:
1.present跳转游戏界面
2.使用web为容器承载游戏引擎
3.容器(这里为controller)增加横屏代码

#pragma mark 强制横屏(针对present方式)
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return (UIInterfaceOrientationLandscapeRight | UIInterfaceOrientationLandscapeLeft);
}
 
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskLandscapeLeft;
}
 
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationLandscapeRight;
}

该方案适用于iOS16系统以下,在16系统以上home键及状态栏依旧朝下,横屏失败;
查阅了很多博客,在官方文档中发现 shouldAutorotateToInterfaceOrientation 方法已经弃用;
更替为 shouldAutorotate 方法后依然失效。

解决方案

1.创建单例(RotationManager)用于管理界面横竖屏状态

.h代码

//单例类
+ (instancetype)shareInstance;
//是否横屏
@property (nonatomic, assign) BOOL isRotation;
//当前屏幕状态
+ (UIInterfaceOrientationMask)supportedInterfaceOrientationsType;

.m代码

static RotationManager *_manager;

//单例方法
+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[RotationManager alloc] init];
        _manager.isRotation = NO;
    });
    return _manager;
}
//查询需要的屏幕状态
+ (UIInterfaceOrientationMask)supportedInterfaceOrientationsType{
    if (_manager.isRotation){
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}

2.容器(controller)

- (void)viewDidLoad {
    [super viewDidLoad];
    //开启横屏状态
    [RotationManager shareInstance].isRotation = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //一定要记得关闭横屏状态,不然退出界面后依旧是横屏
    [RotationManager shareInstance].isRotation = NO;
}

- (BOOL) shouldAutorotate {
    return YES;
}
 
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskLandscapeLeft;
}
 
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationLandscapeRight;
}

3.AppDelegate

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    return [RotationManager supportedInterfaceOrientationsType];
}

总结

该方案仅适用于present跳转的界面
push跳转横屏有很多大佬做过分享这里不做累述
有更好的优化方案麻烦诸位大佬指点指点!!!Thanks♪(・ω・)ノ

你可能感兴趣的:(iOS 界面强制横屏)