ios进阶酷iOS DeveloperiOS开发技能

竖屏iOS应用中强制部分页面横屏的方法

2016-07-27  本文已影响3314人  山是水的故事

需求

今天在使用B站的ijkmedia做视屏播放的功能,视频播放的那个页面我想强制让他横屏。当前的应用本来是一个竖屏应用。查了各种网站方法很多种,但是很多都有各种问题,不符合当前的场景。最终找到了一个解决办法。

处理方法

1 UINavagationController

由于当前的屏幕状态是通过UINavagationController来控制的,所以我们首先需要自定义一个UINavagationController:

@implementation XddBaseNavagationVC

- (BOOL)shouldAutorotate
{
 return [self.viewControllers.lastObject shouldAutorotate];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
 return [self.viewControllers.lastObject supportedInterfaceOrientations];
}

@end

这么做是为了当从横屏页面返回之后,能够让页面保持竖屏(其实是去获取返回之后VC的屏幕状态)。

2 UITabBarViewController

因为当前的应用是一个tabbar应用,所以我们也需要保证tabbar能够正常的显示。我使用了一个分类来处理这个问题,tabbarvc的状态依赖当前选中的VC的属性:

@implementation LCTabBarController (Autorotate)

- (BOOL)shouldAutorotate
{
 return [self.selectedViewController shouldAutorotate];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
 return [self.selectedViewController supportedInterfaceOrientations];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
 return [self.selectedViewController preferredInterfaceOrientationForPresentation];
}

@end

3 BaseVC

然后在我的整个应用中,BaseVC是所有的VC的基类,通过这个我统一的处理了一些问题,因为当前的应用是竖屏的,所以在BaseVC中实现如下几个函数,保证VC竖屏显示:

// 只支持竖屏
- (BOOL)shouldAutorotate {
 return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
 return UIInterfaceOrientationMaskPortrait;
}

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
 return UIInterfaceOrientationPortrait;
}

4 横屏VC的处理

我的横屏的VC也是继承了BaseVC,如果不处理,也会竖屏。通过以下代码进行特殊处理,覆盖BaseVC中的几个方法:

- (BOOL)shouldAutorotate {
 return YES;
}

- (UIInterfaceOrientationMask) supportedInterfaceOrientations {
 return UIInterfaceOrientationMaskLandscapeRight;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
 return UIInterfaceOrientationLandscapeRight;
}

这样就能让他正确的横屏显示,并且返回回去仍然是竖屏。

注意点

当在弹出横屏的VC的时候一定要注意以下几点:

  1. 当前的方式只支持模态弹出。push是会出问题的。
    2.弹出方法,必须要用XddBaseNavagationVC进行包装才可以使用,否则会导致返回之后竖屏的页面变成横屏。
 UINavigationController *nav = [[XddBaseNavagationVC alloc]initWithRootViewController:[[IJKVideoViewController alloc] initWithURL:url]];
 
    [viewController presentViewController:nav animated:YES completion:completion];
上一篇 下一篇

猜你喜欢

热点阅读