1.xib cell
1 先 property cell
@property (nonatomic, strong) ZHCalculateTableViewCell *prototypeCell;
2.获取cell
self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
3.计算cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
ZHCalculateTableViewCell *cell = self.prototypeCell;// 必须将对象传给一个新对象
cell.contentView.translatesAutoresizingMaskIntoConstraints = NO;
[self configureCell:cell atIndexPath:indexPath];//必须先对Cell中的数据进行配置使动态计算时能够知道根据Cell内容计算出合适的高度
/*------------------------------重点这里必须加上contentView的宽度约束不然计算出来的高度不准确-------------------------------------*/
CGFloat contentViewWidth = CGRectGetWidth(self.tableView.bounds);
NSLayoutConstraint *widthFenceConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:contentViewWidth];
[cell.contentView addConstraint:widthFenceConstraint];
// Auto layout engine does its math
CGFloat fittingHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
[cell.contentView removeConstraint:widthFenceConstraint];
return fittingHeight+2*1/[UIScreen mainScreen].scale;//必须加上上下分割线的高度
}
2.Masonry
1.第一种直接在cell里加一个加号方法
+(CGFloat)heightWithModel:(TestModel*)model{
TestCell*cell=[[TestCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:@""];
[cellconfigCellWithModel:model];
[celllayoutIfNeeded];
CGRectframe=cell.descLabel.frame;
returnframe.origin.y+frame.size.height+20;
}
2.用UITableView+FDTemplateLayoutCell计算
git地址 https://github.com/yolii/Masonry-FDTemplateLayoutCell
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{return [tableView fd_heightForCellWithIdentifier:kYLLayoutTableViewCell cacheByIndexPath:indexPath configuration:^(YLLayoutTableViewCell *cell) {
[cell setFeed:[self.viewModel.feedArray objectAtIndex:indexPath.row]];
}];
}
3.自适应,在cell里就把cell.contentView的大小约束对
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewAutomaticDimension;
}