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

本文介绍了一种通过UILabel的width属性动态计算UILabel高度的方法,利用sizeToFit调整UI元素大小,避免界面卡顿,适用于需要自适应布局的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

  • 文章很简单,就是通过给定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];
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值