如何在heightForRowAtIndexPath中获取UITableViewCell?

如何在heightForRowAtIndexPath方法中获取UITableViewCell ,即给定indexPath?

(然后我可以访问我创建的内容视图以增加其高度)

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { // How to get the UITableViewCell associated with this indexPath? } 

谢谢

编辑:事实上,确实有一个有效的方法来做到这一点? 当我输入一些NSLog语句时,似乎在调用cellForRowAtIndexPath之前调用了heightForRowAtIndexPath几次(这是我在单元格中设置UILabels的地方)? 这种意味着我可能会尝试使用一种不起作用的技术,即我希望在heightForRowAtIndexPath中访问每个单元格中已创建的标签以获得它们的高度并将它们添加到一起以获得整个单元格行高度,但是如果它们尚未设置(在cellForRowAtIndexPath )然后我想我的方法不能真正起作用?

对于iOS8

 override func viewDidLoad() { super.viewDidLoad() self.tableView.estimatedRowHeight = 80 self.tableView.rowHeight = UITableViewAutomaticDimension } 

要么

 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } 

但对于iOS7 ,关键是自动布局后计算高度,

 func calculateHeightForConfiguredSizingCell(cell: GSTableViewCell) -> CGFloat { cell.setNeedsLayout() cell.layoutIfNeeded() let height = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize).height + 1.0 return height } 

注意:

1)如果有多行标签,请不要忘记将numberOfLines设置为0。

2)不要忘记label.preferredMaxLayoutWidth = CGRectGetWidth(tableView.bounds)

您可以使用tableview的委托而不是tableView本身。

 id cell = [self tableView:tableView cellForRowAtIndexPath:indexPath]; 

在这里查看答案

更新

在新的iOS版本中并使用正确的自动约束,您不再需要引用单元格来计算单元格的高度。

点击这里

https://www.raywenderlich.com/129059/self-sizing-table-view-cells

这个问题毫无意义,因为在

 heightForRowAtIndexPath 

尚未创建单元格。 这是tableView的工作原理:

  1. TableView询问它的数据源它将具有多少部分。 -numberOfSectionsInTableView
  2. 询问它的数据源每个部分将有多少行(要知道滚动器应该有多大等等) -numberOfRowsInSection
  3. 询问每个可见行的委托高度。 了解细胞的位置。 - heightForRowAtIndexPath
  4. 最后,它要求datasource给它一个单元格来显示给定的索引路径-cellForRowAtIndexPath

因此,您无法从heightForRowAtIndexPath访问单元格,因为尚未创建最可能的单元格。


但是,如果我误解了你的问题,请尝试:

 UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

显而易见的答案是调用cellForRowAtIndexPath ,但您可能已经发现存在一些问题。 如果你还没有看到这个问题: UITableView flexible / dynamic heightForRowAtIndexPath

对于我的上一个项目,我使用了UICell的自定义子类并实现了这样的方法。 然后我从table:heightForRowAtIndexPath:调用它table:heightForRowAtIndexPath:在查找该行的内容之后)。

 + (CGFloat) heightOfContent: (NSString *)content { CGFloat contentHeight = [content sizeWithFont: DefaultContentLabelFont constrainedToSize: CGSizeMake( DefaultCellSize.width, DefaultContentLabelHeight * DefaultContentLabelNumberOfLines ) lineBreakMode: UILineBreakModeWordWrap].height; return contentHeight + DefaultCellPaddingHeight; } 

我建议你计算table:heightForRowAtIndexPath:中行的正确高度table:heightForRowAtIndexPath:使用你的数据结构(文本高度,图像,多个文本等…)。

并在-(void) layoutSubviews方法中更改组件高度。

如果要访问单元格,请使用标记。 但正如@Jhaliya所说,根据细胞内容计算高度更好。 如果您关注单元格的位置,那么我建议您使用滚动视图并在您想要的任何地方自己实现单元格。