0

我正在创建一个类似 facebook 的应用程序。我想根据内容调整单元格的高度。tableviewcell 由UIImageViewUILabel组成UIButton。我可以通过使用委托来调整单元格的高度heightForRowAtIndexPath,但是,有时某个单元格中没有图像。

据我所知,heightForRowAtIndexPath是先叫的。所以,我不能传递在cellForRowAtIndexPath.

我想知道我是否可以在heightForRowAtIndexPathinside传递对象的高度cellForRowAtIndexPath

4

4 回答 4

0

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

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

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

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

于 2014-07-24T06:33:46.413 回答
0

正确的解决方案是:

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

创建一个吸气剂:

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

 return _prototypeCell;
}

将所有与单元格配置相关的代码移动到单元cellForRow格类(您可以在这里查看:如何访问多个自定义 tableviewcells 中的属性

修改 heightForRow:

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

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

要提高 iOs7 的性能,请使用:

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

    return 300; // or any number based on your estimation
}
于 2014-07-24T06:34:36.957 回答
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
}
于 2014-07-24T06:36:07.520 回答
0

不,你不能,这是快速的答案。

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

从 iOS8 开始,表格将能够使用 Autolayout 导出单元格高度 - 请参阅 WWDC 2014 的表格和集合视图中的新增功能。

于 2014-07-24T06:37:02.463 回答