隨著iPhone X的發(fā)布胞四,界面上變化最大的當(dāng)屬NavigationBar和TabBar吭产,如果我們通過(guò)Frame定義視圖的位置,則需判斷設(shè)備類(lèi)型是否為iPhone X擒权,我們是否可以通過(guò)一種更優(yōu)雅的方式诉植,視圖展示時(shí)不需要關(guān)心設(shè)備類(lèi)型祥国。
-
首先我們介紹幾個(gè)iOS知識(shí)點(diǎn)
-
iOS 11 的 Safe Area
XIB勾選Use Safe Area Layout Guide最低支持的版本iOS9.0
屏幕快照 2017-11-07 下午3.24.35.png
代碼方式實(shí)現(xiàn)SafeArea
@property (nonatomic,readonly) UIEdgeInsets safeAreaInsets API_AVAILABLE(ios(11.0),tvos(11.0));
image.png-
Top Layout Guide 和 Bottom Layout Guide
topLayoutGuide.length:表示當(dāng)前頁(yè)面的上方被status bar、navigation bar遮擋的部分晾腔,對(duì)應(yīng)safeAreaInsets.top
bottomLayoutGuide.length:表示當(dāng)前頁(yè)面的下方被TabBar舌稀、ToolBar遮擋的部分,對(duì)應(yīng)safeAreaInsets.bottom
這兩個(gè)屬性屬于ViewController
-
-
實(shí)現(xiàn)
-
思路
是否我們可以給UIViewController增加一個(gè)視圖(ContentView)灼擂,ContentView根據(jù)SafeArea自動(dòng)適應(yīng)壁查,其它的視圖添加到ContentView,這樣就不需要關(guān)心導(dǎo)航欄和TabBar的高度
創(chuàng)建基類(lèi)ViewController剔应,ViewController添加一個(gè)視圖睡腿,該視圖針對(duì)SafeArea做好約束條件,項(xiàng)目中所有的Controller都繼承這個(gè)類(lèi)峻贮,這種方式侵入性太強(qiáng)
通過(guò)Category的方式席怪,UIViewController增加一個(gè)視圖屬性,當(dāng)Controller中添加視圖時(shí)纤控,都增加到Category類(lèi)中的這個(gè)視圖上挂捻,這種方式,如果用戶不調(diào)用Category增加的視圖船万,不對(duì)Controller有任何影響
-
代碼
-
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
-
使用
- (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);
}];
}
注意如果項(xiàng)目首頁(yè)展示UICollectionView刻撒,啟動(dòng)頁(yè)狀態(tài)欄默認(rèn)隱藏,這時(shí)候再進(jìn)入到首頁(yè)UICollectionView中的cell展示出現(xiàn)問(wèn)題耿导,我們需要特殊處理
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
[self.collectionView.collectionViewLayout invalidateLayout];
}
完整的使用例子可以參考:
https://github.com/cheyongzi/SafeArea
覺(jué)得還不錯(cuò)的可以給個(gè)Star