在UITableViewDelegate方法heightForRowAtIndexPath中获取表视图单元属性:

时间:2012-02-20 15:27:14

标签: ios uitableview

我有一个包含自定义表格视图单元格的表视图。它们的高度取决于单元格中显示的文本量。这是我的UITableViewDelegate方法heightForRowAtIndexPath的代码:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];

    NSDictionary *factor = [self.factorsArray objectAtIndex:row];

    CGSize maximumLabelSize = CGSizeMake(260, kMaximumFactorLabelHeight);
    CGSize labelSize = [[factor objectForKey:@"text"] sizeWithFont:[UIFont fontWithName:@"Arial-BoldMT" size:14.0]
                                 constrainedToSize:maximumLabelSize
                                     lineBreakMode:UILineBreakModeWordWrap];

    return (labelSize.height + 72);
}

此代码完美无缺。我的问题是这里有许多硬编码:

  • 表格视图单元格中的标签宽度
  • 字体名称
  • 字体大小
  • “72”这是除了标签高度之外需要添加到单元格的额外高度。

我可以从包含自定义表格视图单元格的xib文件中获取所有这些信息。但是如何在heightForRowAtIndexPath中获取它?我试过 - (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath但我遇到了崩溃,我相信因为当调用heightForRowAtIndexPath方法时单元格还不存在。

1 个答案:

答案 0 :(得分:2)

有几种方法可以做到。我通常在UITableViewCell子类上有一个类方法,根据传入的内容返回高度。

相关问题