强制横屏问题处理

2021-01-20  本文已影响0人  DSA碼侬

最近需求是开发一款智能游戏控制器GameVController 放入app内,要求必须横屏显示:
环境:
1、TARGETSDeployment InfoDevice Orientation如下:

设置1.png
2、GameVController不用导航控制器包装(为什么?后面讲), 模态方式弹出:
GameViewController *gameVC = [[GameViewController alloc] init];
gameVC.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:gameVC animated:YES completion:nil];

解决办法:

在游戏控制器GameVController内,添加以下代码:

# 1、在返回(dismiss)按钮点击事件上
- (void)backBtnClick:(UIButton *)btn{
    // 消失游戏控制器
    [self dismissViewControllerAnimated:YES completion:^{
        // 强制设备横屏转竖屏(UIDevice的类扩展,下文提供)
        [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
    }];
}

# 2、再添加其他方法:
/**
 * 默认所有都不支持转屏,如需个别页面支持除竖屏外的其他方向,请在viewController重写下面这三个方法
 */
// 是否支持自动转屏
- (BOOL)shouldAutorotate{
    return NO; // NO
}
// 支持哪些屏幕方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscapeRight; // 保持一致横屏
}
// 默认的屏幕方向(当前ViewController必须是通过模态出来的UIViewController(模态带导航的无效)方式展现出来的,才会调用这个方法)本控制器不用导航控制器
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationLandscapeRight; // 保持一致横屏
}

注:
1、UIDevice的扩展类:

#1、UIDevice+QDDevice.h文件
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIDevice(QDDevice)

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


#2、UIDevice+QDDevice.m文件
#import "UIDevice+QDDevice.h"

@implementation UIDevice(QDDevice)

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

    NSNumber *orientationTarget = [NSNumber numberWithInteger:interfaceOrientation];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    
}@end

2、为什么GameVController不用push方式展示游戏导航控制器:
实践证明这样以上的两个方法
(-(UIInterfaceOrientationMask)supportedInterfaceOrientations
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation)
不会被调用, 横屏失败。再说了游戏界面本身也是不需要导航栏的。
若有不对,请指正,万分感激!

上一篇下一篇

猜你喜欢

热点阅读