iOS开发设置指定页面横屏显示,其余页面竖屏显示

iOS开发设置指定页面横屏显示,其余页面竖屏显示

假设跳转逻辑为:从A页面跳转至B页面,B页面需要始终横屏显示,其余页面使用竖屏显示;

  • 配置AppDelegate.m

    #import "BViewController.h"
    
    // 配置页面方向
    - (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
        UIViewController *currentVC = [self getCurrentVC];
        if (currentVC && [currentVC isKindOfClass:[BViewController class]]) {
            return UIInterfaceOrientationMaskLandscapeRight;
        }
        return UIInterfaceOrientationMaskPortrait;
    }
    
    // 获取当前显示的ViewController
    - (UIViewController *)getCurrentVC {
        UIViewController *rootVC = self.window.rootViewController;
        if (!rootVC || ![rootVC isKindOfClass:[UINavigationController class]]) {
            return nil;
        }
        UINavigationController *rootNav = (UINavigationController *)rootVC;
        UITabBarController *tab = (UITabBarController *)rootNav.topViewController;
        if (!tab || ![tab isKindOfClass:[UITabBarController class]]) {
            return nil;
        }
        UINavigationController *nav = tab.selectedViewController;
        if (!nav || ![nav isKindOfClass:[UINavigationController class]]) {
            return nil;
        }
        UIViewController *currentVC = nav.topViewController;
        return currentVC;
    }
    

    说明: getCurrentVC方法用于获取当前显示的ViewController, 我这里使用的导航结构为:

    • UINavigationController
      • UITabBarController
        • UINavigationController

    这里需要根据具体的导航结构修改getCurrentVC方法实现;

  • 配置AViewController.m

    - (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];
        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    }
    
    // 重要:必须加此方法
    - (UIInterfaceOrientationMask)supportedInterfaceOrientations {
        return UIInterfaceOrientationMaskPortrait;
    }
    

    说明: 如果不添加supportedInterfaceOrientations方法可能会导致从B页面返回A页面时A页面横屏显示,需要旋转下屏幕才会恢复,此处期望的是返回A页面时竖屏显示;

  • 配置BViewController.m

    - (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];
        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    }
    

到这里就已经配置完成了,B页面会始终横屏显示,其余页面始终竖屏显示;

  • 调试中遇到的坑
    错误配置: 勾选Device Orientation:
    在这里插入图片描述

说明: 这里是否勾选,对屏幕横竖屏显示没有影响,但是会影响启动页显示;如果这里勾选了横屏显示,当手机横屏放置时启动App,启动页会横屏显示;解决办法就是取消此处的横屏勾选。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jinrui_w

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值