iOS9横屏竖屏设置

来源:互联网 发布:淘宝天下天下网商区别 编辑:程序博客网 时间:2024/06/08 06:44
公司App里面有个需求,即所有界面都是竖屏,且不允许横屏切换,唯独有一个播放视频的界面允许横屏,大家都知道视频播放适配最大的播放屏幕那样是最好的。从网上多方查找资料,查到了这么一篇文章:
  1. 最终,根据此需求处理如下: 首先,确保App本身应该允许转屏切换:
    这里写图片描述

  2. 我的App里面UITabBarController是根视图控制器,所以首先创建一个UITabBarController的子类,并设定允许转屏:
    (这些要放在根视图控制器里面, 如果你的应用根视图是UINavigationController, 就放在那里面就好)

#pragma mark 转屏方法重写//返回支持的方向 -(UIInterfaceOrientationMask)supportedInterfaceOrientations{    return [self.viewControllers.firstObject supportedInterfaceOrientations];}//是否自动旋转,返回YES可以自动旋转 -(BOOL)shouldAutorotate{    return self.viewControllers.firstObject.shouldAutorotate;}

3.接着,我的tabbarController里面每个子控制器又都是UINavigationController进行界面push切换的,所以首先创建一个UINavigationController的子类,并设定允许转屏:

//self.topViewController是当前导航显示的UIViewController,这样就可以控制每个UIViewController所支持的方向啦!-(BOOL)shouldAutorotate{    return [self.topViewController shouldAutorotate];}- (UIInterfaceOrientationMask)supportedInterfaceOrientations {    return [self.topViewController supportedInterfaceOrientations];}

4.在你想转屏切换的ViewController上可以照这样重写(允许左右横屏以及竖屏):

- (BOOL)shouldAutorotate {    return NO;}- (UIInterfaceOrientationMask)supportedInterfaceOrientations {    return UIInterfaceOrientationMaskPortrait;}

5.到视频播放界面要设置为横屏啦(我的视频播放只要横屏就好^_^)

// 是否支持屏幕自动旋转,YES自动旋转- (BOOL)shouldAutorotate {    return NO;}- (UIInterfaceOrientationMask)supportedInterfaceOrientations {    return UIInterfaceOrientationMaskLandscape;}//返回优先方向 -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {    return UIInterfaceOrientationLandscapeRight;}

注意:跳转到播放器要使用模态进来, 用Push不会横屏。具体原因不清楚,有了解的麻烦告知一下
[self presentViewController:playerVC animated:YES completion:nil];

总结

  • 如果需求仅仅是少量几个控制器横屏显示,可以定义一个UIViewController的子类作为你的BaseViewController,其他控制器继承自他就好了,只在需要横屏的重写那是3个方法,不用每个控制器都写
  • demo地址

还有一种比较霸道的私有方法,方便实用,但是听说有风险,容易被拒

#pragma - 屏幕屏幕方向- (void)interfaceOrientation:(UIInterfaceOrientation)orientation {    // arc下    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 = orientation;        [invocation setArgument:&val atIndex:2];        [invocation invoke];    }}## 直接在当前控制器调用就行,支持push方式的控制器跳转
0 0