iOS全局禁止横屏,特定页面允许横屏的解决方法

最近在做一个视频实时监控的app,用到萤石开放平台的SDK来进行开发。萤石的demo里面在特定页面通过简单的几句代码调用就实现了全屏和退出全屏的功能。

//进入全屏
- (IBAction)large:(id)sender
{
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
}
//退出全屏
- (IBAction)largeBack:(id)sender
{
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
}

而我在按照萤石官方文档一步一步将SDK导入我的工程,却出现无法全屏的问题。

在参考了iOS 屏幕方向那点事儿UIWebView 全屏播放视频解决办法几篇博文之后,最后采用如下方法解决了全屏问题:

1. 全局禁止横屏

在appdelegate.h添加以下属性:

/***  是否允许横屏的标记 */
@property (nonatomic,assign)BOOL allowRotation;

appdelegate.m添加如下代码:

-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.allowRotation) {//如果设置了allowRotation属性,支持全屏
        return UIInterfaceOrientationMaskAll;
    }
    return UIInterfaceOrientationMaskPortrait;//默认全局不支持横屏
}

2. 在需要支持横屏的界面改变allowRotation属性

//进入全屏
-(void)begainFullScreen
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = YES;
}
// 退出全屏
-(void)endFullScreen
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = NO;
    
    //强制归正:
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val =UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}

viewWillAppearviewWillDisappear分别调用以上方法,在该控制器下即可顺利支持全屏。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容