tableView在iOS11默认使用Self-Sizing解决方案

本文介绍了一个iOS开发中遇到的问题:TableView在iOS11中默认使用Self-Sizing特性,导致高度计算不准确。通过Runtime机制修改UITableView初始化方法,统一关闭Self-Sizing特性,避免手动更改每个TableView。

tableView在iOS11默认使用Self-Sizing

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

解决办法简单粗暴,就是实现对应方法或把这三个属性设为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

 

转载于:https://www.cnblogs.com/huaixu/p/7767200.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值