根据文本内容的高度设置单元格的高度

Set the height of the cell according to the height of the text content

我有一个 table 包含动态单元格。在每个单元格中,我都有 textLabel 和 detailTextLabel。我想将单元格高度设置为 textLabel 的高度之和,detailTextLabel.This 是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

cell.textLabel.numberOfLines = 0;

cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;

cell.detailTextLabel.numberOfLines = 0;

cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;

cell.textLabel.text=text;

cell.detailTextLabel.text=detailText;


return cell;
}

我该怎么做?

以下代码用于 UILabel 的动态高度。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath   *)indexPath{
          if ( [detailText length] <= 0 ){
            CGSize constraint = CGSizeMake(450, 40000.0f);
            CGSize size = [detailText sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14] constrainedToSize:constraint lineBreakMode:UILineBreakModeCharacterWrap];
            size.height = MAX(size.height,36);

            return 50+size.height;
        }
    return 150;
}

希望这有助于解决您的问题。

如果您在 iOS8 上使用 AutoLayout,一个重要的部分是将 UITableView 设置为 "autolayouted":

self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 50.0; // your estimated average cell height

此外,最好使用自定义单元格并覆盖方法 "layoutSubviews":

- (void)layoutSubviews
{
    [super layoutSubviews];

    // Make sure the contentView does a layout pass here so that its subviews have their frames set, which we
    // need to use to set the preferredMaxLayoutWidth below.
    [self.contentView setNeedsLayout];
    [self.contentView layoutIfNeeded];


    self.details.preferredMaxLayoutWidth = CGRectGetWidth(self.details.frame);
}

在 github 查看这个 Example Project