最近需求是開發(fā)一款智能游戲控制器GameVController 放入app內(nèi),要求必須橫屏顯示:
環(huán)境:
1、TARGETS中Deployment Info的Device Orientation如下:

設(shè)置1.png
2、
GameVController不用導(dǎo)航控制器包裝(為什么?后面講), 模態(tài)方式彈出:
GameViewController *gameVC = [[GameViewController alloc] init];
gameVC.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:gameVC animated:YES completion:nil];
解決辦法:
在游戲控制器GameVController內(nèi),添加以下代碼:
# 1、在返回(dismiss)按鈕點擊事件上
- (void)backBtnClick:(UIButton *)btn{
// 消失游戲控制器
[self dismissViewControllerAnimated:YES completion:^{
// 強制設(shè)備橫屏轉(zhuǎn)豎屏(UIDevice的類擴展,下文提供)
[UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
}];
}
# 2、再添加其他方法:
/**
* 默認(rèn)所有都不支持轉(zhuǎn)屏,如需個別頁面支持除豎屏外的其他方向,請在viewController重寫下面這三個方法
*/
// 是否支持自動轉(zhuǎn)屏
- (BOOL)shouldAutorotate{
return NO; // NO
}
// 支持哪些屏幕方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskLandscapeRight; // 保持一致橫屏
}
// 默認(rèn)的屏幕方向(當(dāng)前ViewController必須是通過模態(tài)出來的UIViewController(模態(tài)帶導(dǎo)航的無效)方式展現(xiàn)出來的,才會調(diào)用這個方法)本控制器不用導(dǎo)航控制器
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return UIInterfaceOrientationLandscapeRight; // 保持一致橫屏
}
注:
1、UIDevice的擴展類:
#1、UIDevice+QDDevice.h文件
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIDevice(QDDevice)
/**
* @interfaceOrientation 輸入要強制轉(zhuǎn)屏的方向
*/
+ (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方式展示游戲?qū)Ш娇刂破鳎?br>
實踐證明這樣以上的兩個方法
(-(UIInterfaceOrientationMask)supportedInterfaceOrientations
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation)
不會被調(diào)用, 橫屏失敗。再說了游戲界面本身也是不需要導(dǎo)航欄的。
若有不對,請指正,萬分感激!