之前整个App是只支持竖屏的,一个功能性App要啥横屏啊,突然有一天有人心血来潮要在App中浏览文件的时候支持横屏,那就加吧,记录一下:
iOS App支持横竖屏切换需要在三个地方调整
-
工程文件中需要勾选Landscape Left和Landscape Right
App Delegate中需要实现
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
方法:
AppDelegate.h文件中添加属性allowRotate
,用以告诉系统什么时候支持横屏
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, assign) BOOL allowRotate;
@end
AppDelegate.m
文件中增加以下代码
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (self.allowRotate) {
return UIInterfaceOrientationMaskAll;
}
return UIInterfaceOrientationMaskPortrait;
}
- 在需要支持旋转的页面
testController.m
中添加以下代码:
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
// 启用转屏功能
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
delegate.allowRotate = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// 关闭转屏功能
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
delegate.allowRotate = NO;
// 离开页面时将App切回竖屏
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}
做完以上操作之后,testController此时就已经支持转屏了,如果不能转屏,需查看一下手机控制中心的屏幕方向锁定开关是否打开。
以上这些做完后,多数情况下很可能是不够的,尤其是当我们的页面布局是使用frame写死的情况,如果是用Masonry或snapkit布局的很可能还会出现崩溃的问题issue491。
有些文章会通过以下两个方法开启监听屏幕旋转来实现页面适配
UIKIT_EXTERN NSNotificationName const UIDeviceOrientationDidChangeNotification;
- (void)beginGeneratingDeviceOrientationNotifications;
- (void)endGeneratingDeviceOrientationNotifications;
但是这里我们不这样做,我们用另一种方式实现,屏幕旋转时会触发- (void)viewWillLayoutSubviews
方法,我们在这里重新布局即可。
// 注意,我们在初始化时候已经添加约束
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
}];
}
...
...
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
// 注意这里是remake
[self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
}];
}
至此,在一个竖屏App中个别页面实现转屏支持的操作已全部完成。