前言
在iPhone X设备带有tabBar的页面,如果控制器的hidesBottomBarWhenPushed属性为YES,进行push操作之后,便会出现如下的一些问题,于是我查看了一次苹果系统的一些应用,发现它们是不隐藏tabBar的,估计是苹果就是不希望我们去隐藏它的tabBar。
demo下载
点击下载demo源代码
问题描述:
1、iPhone X push后,tabBar偏移
异常显示效果:
2、iPhone X modal并返回之后, 再push后,tabBar偏移
在带有tabBar的页面,模态弹出(presentViewController)并返回后,再任意执行push操作,便会出现如下异常
异常显示效果:
解决问题:
1、自定义的BaseTabBar
创建自定义的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
谢谢!