ios强制横屏

来源:互联网 发布:ios横版动作游戏 知乎 编辑:程序博客网 时间:2024/05/14 15:04

需求是,我们的工程中大部分页面都是不支持横屏的,但是某一个页面需要强制横屏,不管用户是否开启了屏幕锁定,到这个页面都强制将屏幕转过来,实现方法如下

1、在工程中选择要支持的方向

2、我们的工程师navigationController+tabbar+vc这样的形式

在要实现屏幕横屏的页面加入以下

//强制屏幕为横屏-(void)viewWillAppear:(BOOL)animated{//    NSNumber *orientationUnknown = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];//    [[UIDevice currentDevice] setValue:orientationUnknown forKey:@"orientation"];        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];}-(void)viewWillDisappear:(BOOL)animated{    NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];}//支持的方向-(UIInterfaceOrientationMask)supportedInterfaceOrientations{    return UIInterfaceOrientationMaskLandscapeLeft;}
3、整个工程是由导航tabbar控制的,关键代码粘一下,其中

EHZMainTabBarController是继承自UITabBarController

EHZMainTabBarController *homeTabBarVC = [[EHZMainTabBarController alloc] init];    self.window.rootViewController = homeTabBarVC;
在EHZMainTabBarController中定义工程结构大致如下
UIViewController *homeVC = [[EHZHomeViewController alloc] init];    homeVC.hidesBottomBarWhenPushed = NO;    EHZBaseNavigationController *homeNavigationVC = [[EHZBaseNavigationController alloc] initWithRootViewController:homeVC];
self.viewControllers = @[homeNavigationVC, consultationNavigationVC, discussNavigationVC, personalNavigationVC];


EHZBaseNavigationController是继承自UINavigationController

4、在EHZMainTabBarController和EHZBaseNavigationController重写以下方法

-(BOOL)shouldAutorotate{    if ([EHZCommonUtil canRotateView]) {        return YES;    }    return NO;//    return EHZRootNavigationController.topViewController.shouldAutorotate;}//支持的方向- (UIInterfaceOrientationMask)supportedInterfaceOrientations {    if ([EHZCommonUtil canRotateView]) {        return EHZRootNavigationController.topViewController.supportedInterfaceOrientations;;    }    return UIInterfaceOrientationMaskPortrait;}
5、canRotateView这个方法我专门抽出来谢了一个方法,供全局判断使用,其中EHZSignNameViewController是我需要强制横屏的页面

+ (BOOL)canRotateView{    if ([EHZRootNavigationController.topViewController isKindOfClass:[EHZSignNameViewController class]]){        return YES;}else    return NO;}

以上

0 0