某一个页面强制横屏的方法

需求:登录界面(FirstVC)只能竖屏,进入次级界面(SecondVC)只能横屏。

步骤:

1、新建一个继承UINavigationController类的自定义导航栏类。类中加入此代码

- (BOOL)shouldAutorotate

{

return [self.topViewController shouldAutorotate];

}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{

return [self.topViewController supportedInterfaceOrientations];

}

2、在AppDelegate里用此自定义导航栏类创建实例,并把此实例作为根视图控制器,例如:

FirstVC *firstVC = [[FirstVC alloc] init];

NavVC *navVC = [[NavVC alloc] initWithRootViewController:firstVC];

self.window.rootViewController= navVC;

[self.window makeKeyAndVisible];

FirstVC是第一层控制器,NavVC是自定义导航栏类。

3、从FirstVC跳入次级界面(SecondVC)

-(BOOL)shouldAutorotate

{

return YES;

}

//支持的方向

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {

return UIInterfaceOrientationMaskLandscapeLeft;

}

-(void)viewWillAppear:(BOOL)animated{

NSNumber*orientationUnknown = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];

[[UIDevice currentDevice]setValue:orientationUnknownforKey:@"orientation"];

NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];

[[UIDevice currentDevice]setValue:orientationTargetforKey:@"orientation"];

}

需求达到了。

但是功能实现的时候,也就是横竖屏时会导致屏幕宽高发生交替。导致原有的布局可能出问题

所以在- (void)loadView中添加监听

- (void)loadView{

[super loadView];

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(detectOrientation)name:@"UIDeviceOrientationDidChangeNotification"object:nil];

}

在枚举里添加你加载的View

-(void)detectOrientation

{

UIDevice*device = [UIDevice currentDevice];

switch(device.orientation) {

case UIDeviceOrientationFaceUp:

NSLog(@"朝上平躺");

break;

case UIDeviceOrientationFaceDown:

NSLog(@"朝下平躺");

break;

case UIDeviceOrientationUnknown:

NSLog(@"未知方向");

break;

caseUIDeviceOrientationLandscapeLeft:

//加载视图

.....

break;

caseUIDeviceOrientationLandscapeRight:

NSLog(@"左或者右橫置");

//加载视图

.....

break;

caseUIDeviceOrientationPortrait:

caseUIDeviceOrientationPortraitUpsideDown:

NSLog(@"竖屏");

break;

default:

NSLog(@"未知");

break;

}

}

横屏时,你可能还得隐藏电池栏

//隐藏状态栏

- (BOOL)prefersStatusBarHidden{

return YES;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容