前言
需求是這樣的:
在控制器A中, 不允許轉(zhuǎn)屏, 只能是豎屏
push到控制器B之后, 允許控制器自動轉(zhuǎn)屏幕
實現(xiàn)方式
正常的實現(xiàn)邏輯中, 只需要在控制器A中實現(xiàn)以下
- (BOOL)shouldAutorotate {
return NO;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
就可以實現(xiàn)了
但是今天遇到這么個問題, 無論怎么設(shè)置, 這些代碼也執(zhí)行, 但是都不起作用, 屏幕依然可以旋轉(zhuǎn).
問題
大概的查了一下, 跟UINavigationController, UITabBarController相關(guān)的控制器, 會默認的走這兩個基類的轉(zhuǎn)屏方法, 自己寫的這個就不會生效了, 檢查appDelegate中發(fā)現(xiàn)如下代碼:
LCPlayerViewController *mainViewController = [[LCPlayerViewController alloc] initWithNibName:@"LCPlayerViewController"
bundle:nil];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:mainViewController];
navigationController.navigationBarHidden = YES;
self.navigationController = navigationController;
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
return YES;
解決方法
由于基本是UINavigationController, 所以跟上面說的那個一致, 自己實現(xiàn)的shouldAutorotate等方法不管用了, 于是解決辦法如下:
LECBaseNavigationController *navigationController = [[LECBaseNavigationController alloc] initWithRootViewController:mainViewController];
把創(chuàng)建的Nav變成了自己的一個Nav子類, 定義如下:
#import "LECBaseNavigationController.h"
@interface LECBaseNavigationController ()
@end
@implementation LECBaseNavigationController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (BOOL)shouldAutorotate {
return self.topViewController.shouldAutorotate;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return self.topViewController.supportedInterfaceOrientations;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return self.topViewController.preferredInterfaceOrientationForPresentation;
}
@end
重寫了三個跟轉(zhuǎn)屏相關(guān)的方法, 把轉(zhuǎn)屏的控制歸還給實際的控制器, 再編譯運行, 就可以實現(xiàn)自己的控制器控制自己轉(zhuǎn)屏方向了.
代碼在這
https://github.com/dfzr86/ScreenOrientationsDemo
有問題請加QQ:1547213