tableViewCell根据内容自适应高度的方法

tableViewCell根据内容自适应高度的方法:

无论使用xib还是代码写控件,核心思想都是根据cell中content内容的高度来计算cell的高度。
1.在获取到cell数据源的时候计算内容高度。可以设置一个size属性,用来记录。
2.如果是xib,去掉autolayout
3.在cellForRowAtIndexPath方法中填充cell数据的时候,根据内容高度,设置控件高度
4.在heightForRowAtIndexpath方法中,设置每一个cell 的高度

详细步骤:


       HLComment *comment = [HLComment new];

        comment.floor = obj[@"floor"];

        comment.commentId = obj[@"id"];

        comment.content = obj[@"content"];

//计算content内容高度

        NSDictionary *atrri = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};

        CGRect rect = [comment.content boundingRectWithSize:CGSizeMake(220, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:atrri context:nil];

       comment.size = rect.size;//保存这个高度

//填充cell内容时,根据content高度来设置label高度

- (void)fillCellWithModel:(HLItem *)item{

    ….

    CGRect frame = _content.frame;//_content 是内容label

    frame.size = item.size;

    _content.frame = frame;

    …..

}

另外在heightForRowAtIndexPath 中添加一定的余量。

//自适应cell高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    //NSLog(@"计算cell高度");;



    if (indexPath.row == 0) {

         return self.item.size.height+140;

    }

    HLComment *item = _dataSource[indexPath.row-1];

    return item.size.height+60;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值