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
- UITabBarController
这里需要根据具体的导航结构修改
getCurrentVC
方法实现; - UINavigationController
-
配置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,启动页会横屏显示;解决办法就是取消此处的横屏勾选。