根据内容调整uitableviewcell高度

时间:2014-07-24 06:26:42

标签: ios uitableview heightforrowatindexpath

我正在创建一款类似Facebook的应用。我想根据内容调整单元格的高度。 tableviewcell由UIImageViewUILabelUIButton组成。我可以使用heightForRowAtIndexPath委托来调整单元格的高度,但是,有一段时间某个单元格中没有图像。

据我所知,heightForRowAtIndexPath首次被召唤。因此,我无法传递在cellForRowAtIndexPath中计算的对象高度。

我想知道我是否可以在heightForRowAtIndexPathcellForRowAtIndexPath内传递对象的高度。

4 个答案:

答案 0 :(得分:0)

通常,单元格中图像预览的高度是固定的。您可以在heightForRowAtIndexPath中计算单元格的高度。

如果要使用动态图像大小,则在请求单元格对象时,应从API接收图像高度。在这种情况下,您也可以在heightForRowAtIndexPath中计算单元格的高度。

或者您可以先下载图像并从UImage中检索高度。

通常,我在我的应用中使用第二种或第一种情况。

答案 1 :(得分:0)

正确的解决方案是:

@property (strong, nonatomic) MyCell* prototypeCell;添加到控制器。

创建一个getter:

- (MyCell*) prototypeCell {
  if (!_prototypeCell) {
    _prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:@"MyCell"];
  }

 return _prototypeCell;
}

将与cellForRow的单元格配置相关的所有代码移至Cell类(您可以在此处查看:How to access properties in multiple custom tableviewcells

修改heightForRow:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
  return size.height+1;   
}

适用于autolayout。如果您没有启用自动布局,则可以手动计算。

要提高iOs7的使用效果:

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 300; // or any number based on your estimation
}

答案 2 :(得分:0)

首先调用

heightForRowAtIndexPath。在这里,您必须检查该特定indexPath处的单元格是否具有图像并相应地设置高度。您尚未提供任何代码。但是假设你有一个对象数组,其中包含填充tableView所需的图像和字符串,代码应该看起来像这样:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomObject *object = (CustomObject *)[arrayOfObjects objectAtIndex:indexPath.row];
    if (object.cellImage != null) {
        return 60; //height for row that has image;
    }
    return 44; //those without image
}

答案 3 :(得分:0)

不,你不能,是快速回答。

较慢的答案是在加载任何单元格之前调用高度(或估计高度)方法。在iOS8之前,您需要单独进行高度计算。

从iOS8开始,该表将能够使用Autolayout来获得单元格高度 - 请参阅WWDC 2014的表格和集合视图中的新内容。

相关问题