iOS開(kāi)發(fā)設(shè)置指定頁(yè)面橫屏顯示屈暗,其余頁(yè)面豎屏顯示
假設(shè)跳轉(zhuǎn)邏輯為:從A頁(yè)面跳轉(zhuǎn)至B頁(yè)面,B頁(yè)面需要始終橫屏顯示脂男,其余頁(yè)面使用豎屏顯示养叛;
-
配置AppDelegate.m
#import "BViewController.h" // 配置頁(yè)面方向 - (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { UIViewController *currentVC = [self getCurrentVC]; if (currentVC && [currentVC isKindOfClass:[BViewController class]]) { return UIInterfaceOrientationMaskLandscapeRight; } return UIInterfaceOrientationMaskPortrait; } // 獲取當(dāng)前顯示的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; }
說(shuō)明:
getCurrentVC
方法用于獲取當(dāng)前顯示的ViewController
, 我這里使用的導(dǎo)航結(jié)構(gòu)為:- UINavigationController
- UITabBarController
- UINavigationController
- UITabBarController
這里需要根據(jù)具體的導(dǎo)航結(jié)構(gòu)修改
getCurrentVC
方法實(shí)現(xiàn); - 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; }
說(shuō)明: 如果不添加
supportedInterfaceOrientations
方法可能會(huì)導(dǎo)致從B頁(yè)面返回A頁(yè)面時(shí)A頁(yè)面橫屏顯示宰翅,需要旋轉(zhuǎn)下屏幕才會(huì)恢復(fù)一铅,此處期望的是返回A頁(yè)面時(shí)豎屏顯示; -
配置BViewController.m
- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight]; [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"]; }
到這里就已經(jīng)配置完成了堕油,B頁(yè)面會(huì)始終橫屏顯示潘飘,其余頁(yè)面始終豎屏顯示;
-
調(diào)試中遇到的坑
錯(cuò)誤配置: 勾選Device Orientation:
說(shuō)明: 這里是否勾選掉缺,對(duì)屏幕橫豎屏顯示沒(méi)有影響卜录,但是會(huì)影響啟動(dòng)頁(yè)顯示;如果這里勾選了橫屏顯示眶明,當(dāng)手機(jī)橫屏放置時(shí)啟動(dòng)App艰毒,啟動(dòng)頁(yè)會(huì)橫屏顯示;解決辦法就是取消此處的橫屏勾選搜囱。