需求:登录界面(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;
}