你应该知道的tableViewCell行高计算处理

2020-01-21 07:30:52王振洲


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
 WMSearchResultQAModel *model = self.dataArray[indexPath.row];
 if (model.cellHeight > 0) {
  // 有缓存的高度,取出缓存高度
  return model.cellHeight;
 }
 // 没有缓存时,计算高度并缓存起来
 CGFloat cellHeight; = [WMSearchResultQAModel calutWholeCellHeightWithModel:model];
 // 缓存给model
 model.cellHeight = cellHeight;
 return cellHeight;
}

这样就实现了高度缓存和Model、Cell都对应的优化,我们无需手动管理高度缓存,在添加和删除数据的时候,都是对Model在数据源中进行添加或删除。

而如果使用可变数组或可变字典时,则需要额外的在刷新tableView时对其进行清空处理。

4. 自适应高度

在 iOS8 之后,系统结合autolayout提供了动态结算行高的方法 UITableViewAutomaticDimension,做好约束,我们都不用去实现 heightForRowAtIndexPath 这个代理方法了。

masonry支持毫无压力。

实现步骤:

1、tableView设置


// 预设行高
self.tableView.estimatedRowHeight = xxx;
// 自动计算行高模式 
self.tableView.rowHeight = UITableViewAutomaticDimension;

2、在自定义cell里,masonry布局,比如:


- (void)layoutSubviews {
 [super layoutSubviews];
 [self.headImgView mas_makeConstraints:^(MASConstraintMaker *make) {
  make.top.left.offset(kSpace15);
  make.size.mas_equalTo(CGSizeMake(50.f, 50.f));
  // 在自动计算行高模式下 要加上的 
  make.bottom.equalTo(self.contentView.mas_bottom).offset(-kSpace15);
 }];
 [self.nickNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  make.left.equalTo(self.headImgView.mas_right).offset(12.f);
  make.top.offset(17.f);
 }];
 [self.jobWorkLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  make.left.equalTo(self.nickNameLabel.mas_right).offset(8.f);
  make.right.lessThanOrEqualTo(self.contentView.mas_right).offset(-kSpace15);
  make.top.offset(21.f);
 }];
 [self.hospitalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  make.left.equalTo(self.headImgView.mas_right).offset(12.f);
  make.top.equalTo(self.jobWorkLabel.mas_bottom).offset(6.f);
 }];
 [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
  make.left.right.bottom.offset(0);
  make.height.mas_equalTo(0.5f);
 }];
}