問(wèn)題描述:
iOS11上TableView section之間的間距變的非常大
問(wèn)題原因:
Self-Sizing在iOS11以前的系統(tǒng)是默認(rèn)關(guān)閉的,但是iOS11上是默認(rèn)開(kāi)啟的,Headers, footers, and cells都默認(rèn)開(kāi)啟Self-Sizing,所有estimated 高度默認(rèn)值從iOS11之前的 0 改變?yōu)閁ITableViewAutomaticDimension
解決方案:
iOS11下不想使用Self-Sizing的話,可以通過(guò)以下方式關(guān)閉:
self.tableView.estimatedRowHeight = 0;
self.tableView.estimatedSectionHeaderHeight = 0;
self.tableView.estimatedSectionFooterHeight = 0;
解決方案優(yōu)化:
以上的代碼可以關(guān)閉Self-Sizing,修復(fù)iOS11上TableView的一些顯示bug,但有個(gè)問(wèn)題:如果項(xiàng)目中使用TableView的地方比較多,每一處都要添加上面的代碼,工作量會(huì)比較大,所以上述方案優(yōu)化一下:讓TableView默認(rèn)關(guān)閉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
思路就是通過(guò)Method Swizzling替換TableView的初始化方法,在自定義的初始化方法中關(guān)閉Self-Sizing,這樣只需添加兩個(gè)文件,不用修改其他代碼就可以解決問(wèn)題。
但是替換系統(tǒng)方法還是有一定的風(fēng)險(xiǎn),建議盡量少使用。另外關(guān)于此問(wèn)題不知道大家有沒(méi)有什么更好的方法,還望不吝賜教。
參考文章:
ios 11 tableView適配問(wèn)題
強(qiáng)烈推薦這篇關(guān)于方法交換的文章,寫(xiě)的非常好:
Method Swizzling的各種姿勢(shì)