iOS 给单个控制器添加横竖屏功能

一般直播间 / 视频为了满足用户的需要,都会有小窗播放和全屏播放,下面我说说我的实现方案

  • 点击全屏按钮时,可以通过改变视图的transform及大小来达到横屏的效果,但是这样会有几个问题,一是状态栏没有转成横屏;二是不能感应手机自己的旋转;三是当有键盘弹出时,还是竖屏样式。 所以此方案不是很OK。

iOS 给单个控制器添加横竖屏功能_第1张图片
target屏幕支持方向勾选
  • 一般的项目默认Device Orientation支持Portrait,如果需要某些界面支持横屏可以勾选图上的left 或者 right
  • 在基类控制器需要重写两个方法,防止所有控制器都支持旋转横竖屏。
// 是否支持设备自动旋转
- (BOOL)shouldAutorotate {
    return NO;
}

// 支持屏幕显示方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
  • 在需要横竖屏的控制器重写以下方法,即可响应手机的旋转动作,并且旋转。
// 支持设备自动旋转
- (BOOL)shouldAutorotate {
    return YES;
}

// 支持横屏显示
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    // 如果该界面需要支持横竖屏切换
    return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortrait;
}
  • 如果不能旋转,那么需要查看当前控制器是否有父 NavigationController / TabbarController管理,如果有,则需要在父 NavigationController / TabbarController 重写以下方法支持旋转才可以(或者分类)。
- (BOOL)shouldAutorotate {
   // 返回当前子控制器 是否支持旋转
    return [self.topViewController shouldAutorotate];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
        return [self.topViewController supportedInterfaceOrientations];
}
  • 在切换横竖屏之后,需要对部分子视图更新布局,所以需要监听设备方向的变化并且做出响应。
// 在控制器中添加通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange) name:UIDeviceOrientationDidChangeNotification object:nil];

- (void)deviceOrientationDidChange {
    // 当前是竖屏状态
    if([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait) {
        [self orientationChange:NO];
        //注意: UIDeviceOrientationLandscapeLeft 与 UIInterfaceOrientationLandscapeRight
    } else if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft) {
        [self orientationChange:YES];
    }
}

- (void)orientationChange:(BOOL)landscapeRight {
     if(landscapeRight) {
      // 切换到横屏之后 子视图需要修改的操作

    } else {
     // 切换到竖屏之后 子视图需要修改的操作
    }
}
  • 手动点击切换横竖屏 需要调用setOrientation: ,该方法在iOS3.0后变成私有方法,我们可以通过NSInvocation去调用
- (void)fullScreenButtonClick {
     //屏幕横屏的方法
     SEL selector = NSSelectorFromString(@"setOrientation:");
     NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
     [invocation setSelector:selector];
     [invocation setTarget:[UIDevice currentDevice]];
     // UIInterfaceOrientationPortrait 竖屏的参数
     int val = UIInterfaceOrientationLandscapeRight;
     [invocation setArgument:&val atIndex:2];
     [invocation invoke];
}

有关NSInvocation的介绍

你可能感兴趣的:(iOS 给单个控制器添加横竖屏功能)