最近在做项目时需求是只有在某一个页面可以横竖屏来回切换 其他页面竖屏显示
遇到的问题是在手机横屏的状态下 打开app 页面是错乱的,
下面是我的解决方案
1、在Xcode中进行设置
2、在AppDelegate.h中添加旋转属性
/**
* 是否允许转向
*/
@property(nonatomic,assign)BOOL allowRotation; // 是否允许转向
在AppDelegate.m中添加转屏的代理方法
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window
{
// 如果设置了allowRotation属性,支持全屏
if (_allowRotation == YES) {
return UIInterfaceOrientationMaskAll;
}else{
return UIInterfaceOrientationMaskPortrait;//默认全局不支持横屏
}
}
3、基类navigation代码:
- (BOOL)shouldAutorotate {
return self.topViewController.shouldAutorotate;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return self.topViewController.supportedInterfaceOrientations;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return self.topViewController.preferredInterfaceOrientationForPresentation;
}
4、项目里写了一个公共的UIViewController,名字为BaseViewController,创建的BaseViewController继承UIViewController 在该viewController里进行了如下设置:
-(BOOL)shouldAutorotate{
return YES;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
-(BOOL)shouldAutorotate这个方法是重点 如果设置为NO,在横屏手机的状态下打开app页面还是错乱的
5、如果你的应用的根控制器是TabVC,就把下面这段代码放到TabVC根控制器下,
- (BOOL)shouldAutorotate{
return self.selectedViewController.shouldAutorotate;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return self.selectedViewController.supportedInterfaceOrientations;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return self.selectedViewController.preferredInterfaceOrientationForPresentation;
}
这里就实现了横屏状态下打开app竖屏展示的效果。
如果想在某一个页面里进行横竖屏切换,可以进行如下设置
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[SimplifyAnswerAppDelegate sharedInstance].allowRotation = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[SimplifyAnswerAppDelegate sharedInstance].allowRotation = NO;
}
[SimplifyAnswerAppDelegate sharedInstance]
是我在appdelegate里面写的一个类方法,SimplifyAnswerAppDelegate
是我把appDelegate进行了重新命名,具体方法实现如下:
+ (SimplifyAnswerAppDelegate *)sharedInstance {
return (SimplifyAnswerAppDelegate *)[UIApplication sharedApplication].delegate;
}
如果是用的APPDelegate,可以这么写
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = NO; // 关闭横屏仅允许竖屏
到这里就实现了前面说的所有页面默认竖屏,部分页面横屏显示的需求。