方法一:使用系統自動計算cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell =
[self tableView:tableView cellForRowAtIndexPath:indexPath];
return [cell.contentView systemLayoutSizeFittingSize:
UILayoutFittingCompressedSize].height;
}
方法二:使用第三方庫
下載地址:UITableView-FDTemplateLayoutCell
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellReuseId = [self getReuseIdWithIndexPath:indexPath]; //獲取cell id
CGFloat height = [tableView fd_heightForCellWithIdentifier:cellReuseId cacheByIndexPath:indexPath configuration:^(id cell) {
[self configureCell:cell indexPath:indexPath]; //對cell進行賦值
}];
return height;
}
tips:使用fd的時候需要注意,cell在豎直方向的約束必須要撐滿
舉例說明:cell里面有一個label,進行約束設置.
錯誤示范:
[label mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.equalTo(self.contentView);
make.centerY.equalTo(self.contentView); //豎直方向約束是不滿的,雖然label會有一個本身的高度
}
正確做法:
法一:
[label mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.equalTo(self.contentView);
make.centerY.equalTo(self.contentView);
make.top.bottom.equalTo(self.contentView); //約束撐滿豎直方向
}
法二:
[label mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.contentView);
}];