如何在heightForRowAtIndexPath中获取UITableViewCell?

时间:2011-03-10 02:18:00

标签: iphone ios uitableview heightforrowatindexpath

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

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

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

感谢

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

6 个答案:

答案 0 :(得分:24)

您可以使用tableview的委托代替tableView本身。

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

检查答案here

已更新

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

点击这里

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

答案 1 :(得分:19)

这个问题毫无意义,因为

heightForRowAtIndexPath

尚未创建任何细胞。以下是tableView的工作原理:

  1. TableView询问它的数据源将包含多少部分。 -numberOfSectionsInTableView
  2. 询问它的数据源每个部分将有多少行(要知道卷轴应该有多大等等)-numberOfRowsInSection
  3. 询问每个 可见行 的委托高度。要知道细胞的位置。 - heightForRowAtIndexPath
  4. 最后,它要求datasource给它一个单元格来显示给定的索引路径-cellForRowAtIndexPath
  5. 因此,您无法访问heightForRowAtIndexPath中的单元格,因为尚未创建最可能的单元格。


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

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    

答案 2 :(得分:14)

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

,请参阅此问题

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

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

答案 3 :(得分:4)

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

并使用-(void) layoutSubviews方法更改组件高度。

答案 4 :(得分:1)

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

答案 5 :(得分:-20)

对于 iOS8

override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.estimatedRowHeight = 80
        self.tableView.rowHeight = UITableViewAutomaticDimension
    }

OR

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)