? ? iOS 11下,UITableView的估算高度的屬性,默認(rèn)值從iOS11之前的 0.f 改變?yōu)閁ITableViewAutomaticDimension:(非0.f)。若tableView未使用estimated屬性,tableView的組頭和組尾視圖高度則會(huì)顯示異常。
? ? 修正這個(gè)錯(cuò)誤的方式很簡(jiǎn)單,只需要在創(chuàng)建tableView后,設(shè)置其估算高度為0.f即可。
if(@available(iOS11.0,*)) {
? ? tableView.estimatedRowHeight=0.f;
? ? tableView.estimatedSectionHeaderHeight=0.f;
? ? tableView.estimatedSectionFooterHeight=0.f;
}
? ? 為了解決項(xiàng)目?jī)?nèi)所有tableView或collectionView的該問題,可以使用比較簡(jiǎn)單的方法。
if (@available(iOS 11.0, *)) {
[UITableView appearance].estimatedRowHeight = 0;
[UITableView appearance].estimatedSectionHeaderHeight = 0;
[UITableView appearance].estimatedSectionFooterHeight = 0;
[[UIScrollView appearance]?
setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
}
[UITableView appearance].estimatedSectionHeaderHeight = 0;
[UITableView appearance].estimatedSectionFooterHeight = 0;
另外,也可以使用runtime對(duì)tableview的初始方法進(jìn)行hook,在創(chuàng)建完tableView后,統(tǒng)一為其設(shè)置estimated相關(guān)屬性。代碼如下。
@implementationUITableView (Extention)
+ (void)load {
? ? staticdispatch_once_tonceToken;
? ? dispatch_once(&onceToken, ^{
? ? [HookUtility swizzlingInClass: [self class] originalSelector:@selector(initWithFrame:style:) swizzledSelector:@selector(swizz_initWithFrame:style:)];
? ? });
}
- (__kindof UITableView*)swizz_initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
__kindof UITableView * tableView = [self org_initWithFrame:framestyle:style];
if(@available(iOS11.0,*)) {
tableView.estimatedRowHeight=0.f;
tableView.estimatedSectionHeaderHeight=0.f;
tableView.estimatedSectionFooterHeight=0.f;
}
returntableView;
}
@end
? ? 其中,swizzlingInClass:? originalSelector:swizzledSelector:方法的實(shí)現(xiàn)如下:
+ (void)swizzlingInClass:(Class)cls originalSelector:(SEL)originalSelector swizzledSelector:(SEL)swizzledSelector {
Classclass = cls;
Method originalMethod =class_getInstanceMethod(class, originalSelector);
Method swizzledMethod =class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if(didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
? ? 如果需要設(shè)置iOS 11下scrollView的contentInsetAdjustmentBehavior屬性值為UIScrollViewContentInsetAdjustmentNever的話,可以在設(shè)置估算高度的地方加上下面這行代碼。
tableView.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNeve;
? ? 不過這種hook的方式,在項(xiàng)目中還是盡量少用。