iOS不锁屏下部分页面灵活切换横竖屏,其他页面不会切换

好久没更新文章了,最近项目做到视频直播这块,做视频的话难免需要最大化的处理,现在好多APP最大化都是切换横屏放大的。具体做项目的时候,我们只需要在观看视频的ViewController上面做切换横竖屏就可以了,其他页面只需要竖屏就好了。好吧,首先我先说说如何在项目上做到横竖屏切换然后再说里面的坑吧。

iOS不锁屏下部分页面灵活切换横竖屏,其他页面不会切换_第1张图片
转屏设置.png

首先需要在xcode的 “General” 设置下的Deployment Info进行如何设置。

- (BOOL)shouldAutorotate
{
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}

然后在需要切换横竖屏的ViewController下写下以上代码,即可切换横竖屏。

iOS不锁屏下部分页面灵活切换横竖屏,其他页面不会切换_第2张图片
不锁屏的情况下.png

但是问题来了,在测试阶段,有些人在系统不锁屏的情况下,当手机转向打横的时候其他页面也会跟着切换横屏,这不是我们想见到的。

为什么会出现其他页面也会跟着转向会横屏呢?就目前大多数项目都是用UINavigationController或者是UITabBarController作为RootViewController,就算在子视图上面把shouldAutorotate设置为YES,但是也是会调用回UINavigationController或者是UITabBarController上面的shouldAutorotate。

- (BOOL)shouldAutorotate
{
    if ([self.topViewController isKindOfClass:[AddMovieViewController class]]) { // 如果是这个 vc 则支持自动旋转
        return YES;
    }
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    if ([self.topViewController isKindOfClass:[AddMovieViewController class]]) { // 如果是这个 vc 则支持自动旋转
        return UIInterfaceOrientationMaskAll;
    }
    return UIInterfaceOrientationMaskPortrait;
}

那么可以在自定义的UINavigationController上面按照以上代码写的,当所需要的转屏的ViewController到栈顶的时候,转换横竖屏的设置就会改变,那么在不锁屏的情况下其他ViewController也不会手机转向打横的时候其他页面也会跟着切换横屏。

补充一下如何通过按钮控制横竖屏

- (void)changeScreenAction
{    
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)])
    {
        NSNumber *num = [[NSNumber alloc] initWithInt:(_isFullScreen?UIInterfaceOrientationLandscapeRight:UIInterfaceOrientationPortrait)];
        [[UIDevice currentDevice] performSelector:@selector(setOrientation:) withObject:(id)num];
        [UIViewController attemptRotationToDeviceOrientation];
    }
    SEL selector=NSSelectorFromString(@"setOrientation:");
    NSInvocation *invocation =[NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
    [invocation setSelector:selector];
    [invocation setTarget:[UIDevice currentDevice]];
    int val = _isFullScreen?UIInterfaceOrientationLandscapeRight:UIInterfaceOrientationPortrait;
    [invocation setArgument:&val atIndex:2];
    [invocation invoke];
}

以上就是按钮点击的方法,手动触发切换横竖屏

#pragma mark - 转屏处理逻辑
- (void)viewWillLayoutSubviews
{
    //横屏时候的处理
    if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation))
    {
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        CGFloat height = [UIScreen mainScreen].bounds.size.height;
        
        if (width < height)
        {
            CGFloat tmp = width;
            width = height;
            height = tmp;
        }
        _isFullScreen = YES;
    }
    //竖屏时候的处理
    else
    {
        _isFullScreen = NO;
    }
}

上面是触发横竖屏时候处理UI界面的方法,可以在上面进行UI的处理。

当时做的时候也在网上看了一些博客,iOS7以下应该也要做一些适配,但是我的项目已经是适配iOS7以上的了所以就没做相关适配。如果有哪些地方说得不对可以留言我~希望可以解决部分人的烦恼。

你可能感兴趣的:(iOS不锁屏下部分页面灵活切换横竖屏,其他页面不会切换)