这两天做项目,遇到一个需求,在竖屏的A页面,跳转到横屏的B页面,然后进行手写签名操作。
因为整个项目都没做横屏适配的,如果单纯的打开项目的横屏操作,将会导致在其他页面当用户旋转手机的也会出现横屏,这样布局就会错乱,很影响用户的体验的
所以我们可以这样做,开启项目的横屏功能,然后关闭项目的自动旋转。最后在需要的页面,进行强制旋转操作,这样就解决项目中的这个需求了。
首先打开项目的支持横屏的功能
在xcode里面配置下
修改Appdelegate入口类
- 在.h文件中增加允许旋转属性
/**
* 是否允许转向
*/
@property(nonatomic,assign)BOOL allowRotation;
在.m文件中添加旋转方法,默认竖屏
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window
{ if (self.allowRotation == YES) {
return UIInterfaceOrientationMaskLandscape;
}else{
//竖屏
return UIInterfaceOrientationMaskPortrait;
}
}
为UIDevice写一个分类,写旋转屏幕的方法
.h中
@interface UIDevice (TFDevice)
/**
* @interfaceOrientation 输入要强制转屏的方向
*/
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation;
@end
.m中
#import "UIDevice+TFDevice.h"
@implementation UIDevice (TFDevice)
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation
{
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:interfaceOrientation];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}
@end
在需要旋转的控制器中调用
因为我的当前控制器是模态弹出的,不需要导航栏,可以这样写
在需要旋转的控制器先导入AppDelegate和UIDevice+TFDevice头文件。
并在viewDidLoad调用以下方法
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//允许转成横屏
appDelegate.allowRotation = YES;
//调用横屏代码
[UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeLeft];
[self createSubViews];//初始化UI
}
然后在dismissViewControllerAnimated 之前再次强制旋转竖屏就可以了
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = NO;//关闭横屏仅允许竖屏
//切换到竖屏
[UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
[self dismissViewControllerAnimated:YES completion:nil];
看看效果图