手把手教你怎么如何使用[label sizeToFit]实现最简单的tableView高度自适应

版权声明:欢迎指出错误,作者极懒,常常懒得修改 https://blog.csdn.net/KevinAshen/article/details/84501781

前言

  • 文章很简单,就是通过给定UILabel的宽度,通过[label sizeToFit]来计算出UIlabel的高度
  • 将算出来的高度依次存入数组中,从而实现高度的缓存,避免卡顿
  • 非常简单,缺点就是不太精准,因为有多次的数据转换

参考文章

代码实现

//写在UILabel的扩展类里
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont *)font {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
    label.text = title;
    label.font = font;
    label.numberOfLines = 0;
    [label sizeToFit];
    CGFloat height = label.frame.size.height;
    return height;
}
//自定义cell里
+ (CGFloat)cellComment:(NSString *)comment size:(CGSize)contextSize {
    CGFloat commentHeigth = [UILabel getHeightByWidth:contextSize.width - 80 title:comment font:[UIFont systemFontOfSize:15.0]];
    return commentHeigth + 110;
}
//缓存高度(切忌写在heightOfrow里)
 CGFloat height = [ZDICommitPageTableViewCell cellComment:[_shortCommitPageModel.comments[i] contentCommitStr] size:CGSizeMake(self.view.frame.size.width, 0)];
            NSNumber *commentHeight = [NSNumber numberWithFloat:height];
            [_cellShortCommitHeightArray addObject:commentHeight];
//最好是网络请求到后直接返回主队列就调用
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [_cellLongCommitHeightArray[indexPath.row] floatValue];
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/KevinAshen/article/details/84501781