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;
}