問題描述:
iOS11上TableView section之間的間距變的非常大
問題原因:
Self-Sizing在iOS11以前的系統(tǒng)是默認關閉的,但是iOS11上是默認開啟的晦溪,Headers, footers, and cells都默認開啟Self-Sizing答恶,所有estimated 高度默認值從iOS11之前的 0 改變?yōu)閁ITableViewAutomaticDimension
解決方案:
iOS11下不想使用Self-Sizing的話饺蚊,可以通過以下方式關閉:
self.tableView.estimatedRowHeight = 0;
self.tableView.estimatedSectionHeaderHeight = 0;
self.tableView.estimatedSectionFooterHeight = 0;
解決方案優(yōu)化:
以上的代碼可以關閉Self-Sizing,修復iOS11上TableView的一些顯示bug悬嗓,但有個問題:如果項目中使用TableView的地方比較多污呼,每一處都要添加上面的代碼,工作量會比較大烫扼,所以上述方案優(yōu)化一下:讓TableView默認關閉Self-Sizing曙求。
//
// UITableView+AdapteriOS11.m
// JamBoHealth
//
// Created by zyh on 2018/2/9.
// Copyright ? 2018年 zyh. All rights reserved.
//
#import "UITableView+AdapteriOS11.h"
@implementation UITableView (AdapteriOS11)
+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSel = @selector(initWithFrame:style:);
SEL mySel = @selector(jb_initWithFrame:style:);
Method originalMethod = class_getInstanceMethod(class, originalSel);
Method mySwizzledMethod = class_getInstanceMethod(class, mySel);
BOOL didAddMethod = class_addMethod(class, originalSel, method_getImplementation(mySwizzledMethod),
method_getTypeEncoding(mySwizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
mySel,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, mySwizzledMethod);
}
});
}
- (instancetype)jb_initWithFrame:(CGRect)frame style:(UITableViewStyle)style
{
[self jb_initWithFrame:frame style:style];
self.estimatedSectionHeaderHeight = 0;
self.estimatedSectionFooterHeight = 0;
NSLog(@"jb_initWithFrame:style:");
return self;
}
@end
思路就是通過Method Swizzling替換TableView的初始化方法咧虎,在自定義的初始化方法中關閉Self-Sizing焙糟,這樣只需添加兩個文件歧譬,不用修改其他代碼就可以解決問題涩盾。
但是替換系統(tǒng)方法還是有一定的風險厌殉,建議盡量少使用塔沃。另外關于此問題不知道大家有沒有什么更好的方法阵翎,還望不吝賜教院领。
參考文章:
ios 11 tableView適配問題
強烈推薦這篇關于方法交換的文章双絮,寫的非常好:
Method Swizzling的各種姿勢