iOS轉(zhuǎn)屏控制代碼(shouldAutorotate/supportedInterfaceOrientations)不起作用

前言

需求是這樣的:
在控制器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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容