0

我有一个带有标签的自定义单元格。我想要做的是制作标签sizeToFit并将cellForRow...标签高度传递给一个名为labelHeight. 然后在heightForRow...我想返回labelHeight

问题是,它返回的高度为 0。这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ...
    [customCell.label sizeToFit];
    self.labelHeight = customCell.label.frame.size.height;
    ...
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    return self.labelHeight;
}
4

2 回答 2

0

我不认为有一个很好的解决方案,就像heightForRowAtIndexPath之前所说的那样cellForRowAtIndexPath

你可以:

  • heightForRowAtIndexPath通过计算具有特定字体(样式和大小)的文本量将占用的大小来计算单元格的高度:

    CGSize size = [string sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]}];    
    CGSize adjustedSize = CGSizeMake(ceilf(size.width), ceilf(size.height));
    

或者您可以模拟整个视图以获得更精确的视图(但计算成本会更高)或

  • 计算单元格高度后重新加载表格视图cellForRowAtIndexPath
于 2015-02-16T22:38:50.680 回答
0

如果您需要计算 heightForRowAtIndexPath 最简单的方法(虽然感觉效率低下)是使用 heightForRow...创建单元格,如果您能够使用动态常数简化已知常数的高度计算,这可能会更有效但代码更多。例如。

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath(NSIndexPath *)indexPath{
  NSString *string = self.objects[indexPath.row];
  NSDictionary *textAttributes = nil; //attributes here

  return self.someButton.frame.size.height +
        self.someSwitch.frame.size.height +
        [string boundingRectWithSize:CGSizeMake(LABEL_WIDTH, CGFLOAT_MAX)
                       options:NSStringDrawingUsesLineFragmentOrigin
                    attributes:textAttributes
                       context:nil].size.height;
} 

如果您能够支持 iOS 8+ 并使用自动布局,更好的解决方案是-estimatedRowHeight将 tableView 上的属性设置为非零值,然后单元格上的 UILayoutConstraints 将能够为您计算。这是 iOS8 中 tableViews 的一个非常受欢迎的新增功能,并在其中一个 WWDC 视频中进行了描述。但是如果没有单元格上的自动布局,它就不起作用。

于 2015-02-16T23:31:15.117 回答