TableView iOS11適配->快速關閉Self-Sizing

問題描述:

iOS11上TableView section之間的間距變的非常大

問題原因:

Self-Sizing在iOS11以前的系統是默認關閉的,但是iOS11上是默認開啟的,Headers, footers, and cells都默認開啟Self-Sizing,所有estimated 高度默認值從iOS11之前的 0 改變為UITableViewAutomaticDimension

解決方案:

iOS11下不想使用Self-Sizing的話,可以通過以下方式關閉:

self.tableView.estimatedRowHeight = 0;
self.tableView.estimatedSectionHeaderHeight = 0;
self.tableView.estimatedSectionFooterHeight = 0;

解決方案優化:

以上的代碼可以關閉Self-Sizing,修復iOS11上TableView的一些顯示bug,但有個問題:如果項目中使用TableView的地方比較多,每一處都要添加上面的代碼,工作量會比較大,所以上述方案優化一下:讓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,這樣只需添加兩個文件,不用修改其他代碼就可以解決問題。
但是替換系統方法還是有一定的風險,建議盡量少使用。另外關于此問題不知道大家有沒有什么更好的方法,還望不吝賜教。

參考文章:
ios 11 tableView適配問題
強烈推薦這篇關于方法交換的文章,寫的非常好:
Method Swizzling的各種姿勢

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容