iOS开发-UITableView在iOS11默认使用Self-Sizing造成contentSize计算问题的解决

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值