iOS开发 转屏控制 (shouldAutorotate/supportedInterfaceOrientations)不起作用

需求是这样的:
在控制器A中, 不允许转屏, 只能是竖屏
push到控制器B之后, 允许控制器自动转屏幕

实现方式

正常的实现逻辑中, 只需要在控制器A中实现以下

- (BOOL)shouldAutorotate {
    return NO;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

就可以实现了

但是今天遇到这么个问题, 无论怎么设置, 这些代码也执行, 但是都不起作用, 屏幕依然可以旋转.

问题

大概的查了一下, 跟UINavigationController, UITabBarController相关的控制器, 会默认的走这两个基类的转屏方法, 自己写的这个就不会生效了, 检查appDelegate中发现如下代码:

    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, 所以跟上面说的那个一致, 自己实现的shouldAutorotate等方法不管用了, 于是解决办法如下:

    LECBaseNavigationController *navigationController = [[LECBaseNavigationController alloc] initWithRootViewController:mainViewController];

把创建的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

重写了三个跟转屏相关的方法, 把转屏的控制归还给实际的控制器, 再编译运行, 就可以实现自己的控制器控制自己转屏方向了.
代码在这

https://github.com/dfzr86/ScreenOrientationsDemo



作者:__zimu
链接:https://www.jianshu.com/p/1c8d71deded8
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

猜你喜欢

转载自blog.csdn.net/ljc_563812704/article/details/81901878
今日推荐