前言
在iPhone X設備帶有tabBar的頁面笋除,如果控制器的hidesBottomBarWhenPushed屬性為YES拙吉,進行push操作之后盘榨,便會出現(xiàn)如下的一些問題硬霍,于是我查看了一次蘋果系統(tǒng)的一些應用,發(fā)現(xiàn)它們是不隱藏tabBar的坏快,估計是蘋果就是不希望我們去隱藏它的tabBar铅檩。
demo下載
點擊下載demo源代碼
問題描述:
1、iPhone X push后莽鸿,tabBar偏移
異常顯示效果:
2昧旨、iPhone X modal并返回之后, 再push后祥得,tabBar偏移
在帶有tabBar的頁面兔沃,模態(tài)彈出(presentViewController)并返回后,再任意執(zhí)行push操作级及,便會出現(xiàn)如下異常
異常顯示效果:
解決問題:
1乒疏、自定義的BaseTabBar
創(chuàng)建自定義的BaseTabBar,繼承自UITabBar饮焦,替換TabBarController的tabBar怕吴,代碼如下:
YUBaseTabBar *baseTabBar = [[YUBaseTabBar alloc] init];
[self setValue:baseTabBar forKey:@"tabBar"];
2、重寫tabBar的一些方法
OC代碼
#import "YUBaseTabBar.h"
@implementation YUBaseTabBar
{
UIEdgeInsets _oldSafeAreaInsets;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_oldSafeAreaInsets = UIEdgeInsetsZero;
}
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
_oldSafeAreaInsets = UIEdgeInsetsZero;
}
- (void)safeAreaInsetsDidChange {
[super safeAreaInsetsDidChange];
if (!UIEdgeInsetsEqualToEdgeInsets(_oldSafeAreaInsets, self.safeAreaInsets)) {
[self invalidateIntrinsicContentSize];
if (self.superview) {
[self.superview setNeedsLayout];
[self.superview layoutSubviews];
}
}
}
- (CGSize)sizeThatFits:(CGSize)size {
size = [super sizeThatFits:size];
if (@available(iOS 11.0, *)) {
float bottomInset = self.safeAreaInsets.bottom;
if (bottomInset > 0 && size.height < 50 && (size.height + bottomInset < 90)) {
size.height += bottomInset;
}
}
return size;
}
- (void)setFrame:(CGRect)frame {
if (self.superview) {
if (frame.origin.y + frame.size.height != self.superview.frame.size.height) {
frame.origin.y = self.superview.frame.size.height - frame.size.height;
}
}
[super setFrame:frame];
}
@end
swift代碼
class YUBaseTabBar: UITabBar {
var oldSafeAreaInsets = UIEdgeInsets.zero
@available(iOS 11.0, *)
override func safeAreaInsetsDidChange() {
super.safeAreaInsetsDidChange()
if oldSafeAreaInsets != safeAreaInsets {
oldSafeAreaInsets = safeAreaInsets
invalidateIntrinsicContentSize()
superview?.setNeedsLayout()
superview?.layoutSubviews()
}
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
var size = super.sizeThatFits(size)
if #available(iOS 11.0, *) {
let bottomInset = safeAreaInsets.bottom
if bottomInset > 0 && size.height < 50 && (size.height + bottomInset < 90) {
size.height += bottomInset
}
}
return size
}
override var frame: CGRect {
get {
return super.frame
}
set {
var tmp = newValue
if let superview = superview, tmp.maxY !=
superview.frame.height {
tmp.origin.y = superview.frame.height - tmp.height
}
super.frame = tmp
}
}
}
}
demo查看(https://github.com/timelywind/TabBarFit_iPhoneX_Demo)
參考:https://stackoverflow.com/a/47225653/1553324
謝謝县踢!