因为自动布局和体验的问题,很多 iOS 应用都是只支持竖屏(Portrait)的界面,但有时候我们希望某一个页面同时支持横屏(Landscape),因为有些内容比较长,在横屏的时候可以不需要换行,布局更美观,更合理。
这个时候我先是这样 Google 的。
ios landscape for one view
搜索出来的答案是,首先在你的项目里设置你支持的 Device Orientation。
Device Orientation.png然后在你不支持横屏的页面里禁止自动旋转。
- (BOOL)shouldAutorotate {
return NO;
}
最后在你想要支持横屏的页面里加上下面的代码。
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return UIInterfaceOrientationLandscapeLeft; // or Right of course
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskLandscape;
}
一切都那么完美,编译,运行。
WTF! It's not working!!!
只能继续问 Google 爸爸了,这次我搜索的是。
supportedinterfaceorientations not working
终于找到了问题所在了。
If your are using a UINavigationController as the root window controller, it will be its shouldAutorotate & supportedInterfaceOrientations which would be called.
Idem if you are using a UITabBarController, and so on.
So the thing to do is to subclass your navigation/tabbar controller and override its shouldAutorotate & supportedInterfaceOrientations methods.
因为我使用了 UITabBarController,所以这个实现代码必须写在这里,而不是写在那个你想要实现 Landscape 的页面里面,具体怎么写呢?我这里是 UINavigationController 嵌在了 UITabBarController 里面,所以代码会像下面这样。
-(BOOL)shouldAutorotate {
return YES;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
UINavigationController *navCtl = self.viewControllers[0];
if ([navCtl.topViewController isKindOfClass:[YourViewController class]]) {
return UIInterfaceOrientationMaskAll;
}
return UIInterfaceOrientationMaskPortrait;
}
根据你自己的页面结构,只需要判断 UITabBarController 里面那个 YourViewController 是你想要实现横屏的页面就好了,对于这个页面,我这里所有方向的旋转都支持,对于其它页面,只支持 Portrait。
网友评论