美文网首页iOS开发
iOS开发-UITableView在iOS11默认使用Self-

iOS开发-UITableView在iOS11默认使用Self-

作者: Pandakingli | 来源:发表于2017-11-03 10:40 被阅读1次

UITableView在iOS11默认使用Self-Sizing

UITableView的estimatedRowHeight、estimatedSectionHeaderHeight、 estimatedSectionFooterHeight三个高度估算属性由默认的0变成了UITableViewAutomaticDimension,导致很多地方的TableView高度和contentSize出现了问题。

这个应该是UITableView最大的改变。我们知道在iOS8引入Self-Sizing 之后,我们可以通过实现estimatedRowHeight相关的属性来展示动态的内容,实现了estimatedRowHeight属性后,得到的初始contenSize是个估算值,是通过estimatedRowHeight 乘以 cell的个数得到的,并不是最终的contenSize,tableView就不会一次性计算所有的cell的高度了,只会计算当前屏幕能够显示的cell个数再加上几个,滑动时,tableView不停地得到新的cell,更新自己的contenSize,在滑到最后的时候,会得到正确的contenSize。

解决办法简单粗暴,就是实现对应方法或把这三个属性设为0。

但由于项目中涉及的页面很多,一个一个改起来很繁琐,于是使用了runtime机制替换了initWithFrame和initWithFrame:style:方法,默认将Self-Sizing关闭了

#import <UIKit/UIKit.h>

@interface UITableView (ClosedSelfSizing)

@end

 

#import "UITableView+ClosedSelfSizing.h"
#import <objc/runtime.h>
@implementation UITableView (ClosedSelfSizing)

+(void)load{
    
    /** 获取原始setBackgroundColor方法 */
    Method originalM = class_getInstanceMethod([self class], @selector(initWithFrame:style:));
    
    /** 获取自定义的pb_setBackgroundColor方法 */
    Method exchangeM = class_getInstanceMethod([self class], @selector(initWithNewFrame:style:));
    
    /** 交换方法 */
    method_exchangeImplementations(originalM, exchangeM);
    
    /** 获取原始setBackgroundColor方法 */
    Method originalInt = class_getInstanceMethod([self class], @selector(initWithFrame:));
    
    /** 获取自定义的pb_setBackgroundColor方法 */
    Method exchangeInt = class_getInstanceMethod([self class], @selector(initWithNewFrame:));
    
    method_exchangeImplementations(originalInt, exchangeInt);
}

/** 自定义的方法 */
- (UITableView *)initWithNewFrame:(CGRect)frame style:(UITableViewStyle)style
{
    UITableView * temp = [self  initWithNewFrame:frame style:style];

    temp.estimatedRowHeight = 0;
    temp.estimatedSectionHeaderHeight = 0;
    temp.estimatedSectionFooterHeight = 0;
    return temp;
}
-(UITableView *)initWithNewFrame:(CGRect)frame
{
    UITableView * temp = [self  initWithNewFrame:frame];
    
    temp.estimatedRowHeight = 0;
    temp.estimatedSectionHeaderHeight = 0;
    temp.estimatedSectionFooterHeight = 0;
    return temp;
}
@end

相关文章

网友评论

    本文标题:iOS开发-UITableView在iOS11默认使用Self-

    本文链接:https://www.haomeiwen.com/subject/cbazpxtx.html