适配

iOS 11.0 iPhone X SafeArea向下兼容

2017-11-07  本文已影响107人  cheyongzi

随着iPhone X的发布,界面上变化最大的当属NavigationBar和TabBar,如果我们通过Frame定义视图的位置,则需判断设备类型是否为iPhone X,我们是否可以通过一种更优雅的方式,视图展示时不需要关心设备类型。

UIViewController+SafeArea.h

@interface UIViewController (SafeArea)

@property (nonatomic, strong) UIView    *contentView;

@end
#import "UIViewController+SafeArea.h"
#import <objc/runtime.h>
#import "Masonry.h"

static const void *ContentView = &ContentView;

@implementation UIViewController (SafeArea)

- (void)setContentView:(UIView *)contentView {
    objc_setAssociatedObject(self, ContentView, contentView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIView *)contentView {
    UIView *view = objc_getAssociatedObject(self, ContentView);
    if (!view) {
        view = [UIView new];
        view.backgroundColor = [UIColor clearColor];
        self.contentView = view;
        [self.view addSubview:view];
        
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.equalTo(self.view);
            if (@available(iOS 11.0, *)) {
                make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
                make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
            } else {
                self.automaticallyAdjustsScrollViewInsets = NO;
                make.top.equalTo(self.mas_topLayoutGuide);
                make.bottom.equalTo(self.mas_bottomLayoutGuide);
            }
        }];
    }
    return view;
}

@end
  1. 使用

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"SafeArea";
    
    [self.contentView addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.and.right.equalTo(self.contentView);
    }];
}

注意如果项目首页展示UICollectionView,启动页状态栏默认隐藏,这时候再进入到首页UICollectionView中的cell展示出现问题,我们需要特殊处理

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    [self.collectionView.collectionViewLayout invalidateLayout];
}

完整的使用例子可以参考:

https://github.com/cheyongzi/SafeArea

觉得还不错的可以给个Star

上一篇 下一篇

猜你喜欢

热点阅读