iOS转屏控制分析

在iOS开发中,绝大部分页面都只支持竖屏显示,只有个别页面要支持横屏显示,这种场景很常见。这篇文章我会介绍一下我在开发中是如何灵活控制每个页面的方向的。说明:这篇文章不会介绍api怎么用,只说流程原理,给出我的处理方案,以及我遇到的问题点。

1、转屏流程

1.1、加速计识别设备的旋转方向,发送UIDeviceOrientationDidChangeNotification通知。
1.2、app接受到旋转通知事件。
1.3、app通过AppDelegate通知当前程序的KeyWindow
1.4、KeyWindow会询问他的rootViewController是否可以旋转,支持哪些方向的旋转。
1.5、如果存在modal的viewController,系统则会询问modal的viewController是否可以旋转,支持哪些方向的旋转。

2、如何控制interface orientation (界面方向)

2.1、分析
了解转屏流程后,其实就有思路了,KeyWindow会向rootViewController询问界面旋转方向信息,那么只要rootViewController返回的信息不是写死的,而是根据当前的视图情况动态的返回的,问题就得到解决了。modal出来的viewController也是同样的道理。
例如:rootViewControllerUINavigationController,那么push出来各个不同的页面,UINavigationController都不直接返回界面旋转信息,而是去询问他的栈顶视图控制器的界面旋转信息。因此常规的解决方案一般有两种:

  • UITabBarControllerUINavigaionControllerUIViewController创建一个基类,项目中所有的viewController都继承各自基类,在基类中写死是竖屏的代码,然后子类中根据业务对显示方向的要求重写基类中的方法。
  • category中处理

考虑到采用继承的方式缺点: 侵入性强、必须统一继承基类,一旦没有继承就无法控制界面方向。所以我采用的category方式。

2.2、实现步骤

  • 勾选配置
1514027-134ceef9f48b9a61.png
  • 如果有自定义UINavigaionControllerUITabBarController的话,删除里面控制转屏的代码
- (BOOL)shouldAutorotate;
- (UIInterfaceOrientationMask)supportedInterfaceOrientations;
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation;
  • 添加category
    1514027-12808045e483b9f4.png

    项目中只需引入这几个category,在开发中就不用关心任何界面旋转的问题了,只需要在需要支持特殊方向的viewController中去选择性的override上面的三个方法,返回自己需要支持的方向就行了。
    下面贴一下这几个category的实现:
@implementation UITabBarController (JLRotation)

// 是否自动旋转,返回YES可以自动旋转,返回NO禁止旋转
- (BOOL)shouldAutorotate
{
    return [self.selectedViewController shouldAutorotate];
}

// 返回支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return [self.selectedViewController supportedInterfaceOrientations];
}

// 由模态推出的视图控制器 优先支持的屏幕方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return [self.selectedViewController preferredInterfaceOrientationForPresentation];
}

@end


@implementation UINavigationController (JLRotation)

- (BOOL)shouldAutorotate
{
    return [self.topViewController shouldAutorotate];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return [self.topViewController supportedInterfaceOrientations];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return [self.topViewController preferredInterfaceOrientationForPresentation];
}

@end


@implementation UIViewController (JLRotation)

- (BOOL)shouldAutorotate
{
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

@end

3、遇到的问题

3.1、push的时候不会主动转屏,然而modal的方式是一切正常的。不知道为什么苹果要这样...
场景举例:从viewControllerA push viewControllerBviewControllerA只支持竖屏,假如业务场景要求viewControllerB只支持横屏UIInterfaceOrientationMaskLandscape,当push到viewControllerB的时候,页面不会主动转到横屏,但用户如果主动去旋转手机方向,界面就能正常在指定的方向里旋转了。
解决办法就是在viewControllerBviewDidLoadviewWillAppear中加如下代码,通过代码触发手机屏幕旋转。

[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];
[UIViewController attemptRotationToDeviceOrientation];

这里有个问题,调用了苹果的私有api,有被拒的风险,还有另外一种转屏写法,这段代码也可以封装到自己的私有工具代码库中去:

- (void)setInterfaceOrientation:(UIInterfaceOrientation)orientation
{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        [invocation setArgument:&orientation atIndex:2];
        [invocation invoke];
    }
}

3.2、设备锁屏开关打开,手机横屏摆放,app启动时,首页UI(该页面只支持竖屏)出错。出现了页面是竖屏的,状态栏缺是横屏的现象。

// 设置设置状态栏竖屏
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait];

4、监听interface orientation

至此,基本就能灵活控制各个viewController的显示方向了。不过做到这些还不够,例如腾讯视频,看视频的页面竖屏的时候,video视图部分显示在顶部,横屏的时候或者手动点击全屏按钮的时候,video视图就横屏显示了,这是怎么做到的?常规做法一般两种:

  1. 整个viewController是只竖屏显示的,监听device orientation,对video视图单独做旋转,然后铺满屏幕处理。效果可以参考《今日头条》、《优酷》。不过这样有个弊端,横屏的时候状态栏是没有的,在横屏播放的时候,想通过状态栏看下时间看不到。
  2. viewController支持横竖屏,如果用户在手机设置中锁定了转屏,那么用户点击全屏按钮的时候就通过代码强制转屏。监听device orientation,去重新布局video视图。效果可以参考《腾讯视频》。

不管采用哪种方案,都必须监听设备方向,下面我提供一下监听设备方向的方法:

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
}


- (void)addNotification
{
    if (![UIDevice currentDevice].generatesDeviceOrientationNotifications) {
        [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleStatusBarOrientationChange:)
                                                 name:UIApplicationDidChangeStatusBarOrientationNotification
                                               object:nil];
}

- (void)handleStatusBarOrientationChange:(NSNotification *)notification
{
    UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    if (interfaceOrientation == UIInterfaceOrientationPortrait) {
        NSLog(@"竖屏");
        [self videoViewRotation:NO];
    }
    else if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
        NSLog(@"朝左");
        [self videoViewRotation:YES];
    }
    else if (interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        NSLog(@"朝右");
        [self videoViewRotation:YES];
    } else {
        [self videoViewRotation:NO];
    }
}

// 这段是伪代码,大家根据自己的情况做调整
- (void)videoViewRotation:(BOOL)isFullScreen
{
    if (isFullScreen) {
        [self.videoView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(self.view);
            if (@available(iOS 11.0, *)) {
                make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
                make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
            } else {
                make.left.equalTo(self.view);
                make.right.equalTo(self.view);
            }
        }];
    } else {
        [self.videoView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.view);
            make.height.mas_equalTo(250);
        }];
    }
}

注意我这里监听的是UIApplicationDidChangeStatusBarOrientationNotification状态栏的方向,因为我们真正要处理的是页面方向发生旋转UI的变化。而在设备的物理方向发生旋转的时候,如果此时当前控制器的页面并没有旋转,我们这时改变UI布局,可能就发生问题了。最直接的表现就是会低概率的出现状态栏方向和界面方向显示的不一致,所以监听状态栏方向,根据状态栏方向再来对界面进行处理能保证方向一致。

猜你喜欢

转载自blog.csdn.net/weixin_34080903/article/details/87398815
今日推荐