竖屏应用里面添加横屏页面
2018-05-11 本文已影响17人
muice
需求:
在某个竖屏应用里面有若干横屏。
处理方法
1 UINavagationController
由于当前的屏幕状态是通过UINavagationController来控制的,所以我们首先需要自定义一个BaseNavagationController:
// 这么做是为了当从横屏页面返回之后,能够让页面保持竖屏(其实是去获取返回之后VC的屏幕状态)
-(BOOL)shouldAutorotate
{
return YES;
}
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return [self.viewControllers.lastObject supportedInterfaceOrientations];
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return [self.viewControllers.lastObject preferredInterfaceOrientationForPresentation];
}
2 UITabBarViewController
因为当前的应用是一个tabbar应用,所以我们也需要保证tabbar能够正常的显示。我使用了一个分类来处理这个问题,tabbarvc的状态依赖当前选中的VC的属性:
- (BOOL)shouldAutorotate
{
return [self.selectedViewController shouldAutorotate];
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return [self.selectedViewController supportedInterfaceOrientations];
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return [self.selectedViewController preferredInterfaceOrientationForPresentation];
}
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的时候一定要注意以下几点:
当前的方式只支持模态弹出。push是会出问题的。
- APPDelegate需要添加下面代码
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
return UIInterfaceOrientationMaskAll;
}
注意:听说要用BaseNavagationController进行包装才可以使用,否则会导致返回之后竖屏的页面变成横屏。但是我没有出现这个问题呀!
UINavigationController *nav = [[BaseNavagationController alloc]initWithRootViewController:[[XXXViewController alloc] init]];
[viewController presentViewController:nav animated:YES completion:completion];