1.xib cell
1 先 property cell
@property (nonatomic, strong)? ZHCalculateTableViewCell *prototypeCell;
2.獲取cell
self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
3.計(jì)算cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
ZHCalculateTableViewCell *cell = self.prototypeCell;// 必須將對(duì)象傳給一個(gè)新對(duì)象
cell.contentView.translatesAutoresizingMaskIntoConstraints = NO;
[self configureCell:cell atIndexPath:indexPath];//必須先對(duì)Cell中的數(shù)據(jù)進(jìn)行配置使動(dòng)態(tài)計(jì)算時(shí)能夠知道根據(jù)Cell內(nèi)容計(jì)算出合適的高度
/*------------------------------重點(diǎn)這里必須加上contentView的寬度約束不然計(jì)算出來的高度不準(zhǔn)確-------------------------------------*/
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里加一個(gè)加號(hào)方法
+(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計(jì)算
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.自適應(yīng),在cell里就把cell.contentView的大小約束對(duì)
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewAutomaticDimension;
}