app开发iOS程序员

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

2017-09-18  本文已影响236人  codychen123

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

target屏幕支持方向勾选
// 是否支持设备自动旋转
- (BOOL)shouldAutorotate {
    return NO;
}

// 支持屏幕显示方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
// 支持设备自动旋转
- (BOOL)shouldAutorotate {
    return YES;
}

// 支持横屏显示
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    // 如果该界面需要支持横竖屏切换
    return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortrait;
}
- (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 {
     // 切换到竖屏之后 子视图需要修改的操作
    }
}
- (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的介绍

上一篇下一篇

猜你喜欢

热点阅读