ios - 根据文本量更改 UITableViewCell 高度

我需要能够调整 UITableView 中单个单元格的高度,以使其适合其详细标签中的文本数量。

我玩过以下游戏,但对我不起作用:

How do I wrap text in a UITableViewCell without a custom cell

尝试的代码:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellText = @"Go get some text for your cell.";
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

    return labelSize.height + 20;
}

这不起作用,它在单元格上显示整个字符串,但单元格高度根本不受影响。

最佳答案

很简单,只需将其添加到您的代码中即可:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

它会自动计算行高,然后返回一个 float ... :-)

希望这会有所帮助!

https://stackoverflow.com/questions/9827126/

相关文章:

iphone - 选中时选中的 UItableViewCell 保持蓝色

objective-c - 所有异常断点在模拟器上无缘无故停止

objective-c - 如何本地化 iOS Storyboard

iphone - 在 UITableView 的 iOS 文档目录中列出保存的文件?

ios - UILabel 根据要显示的文本自动调整大小

iphone - 在 bundle 中找不到名为 'Main' 的 Storyboard

iphone - 绘制平滑曲线 - 所需方法

iphone - 如何检查数组是空还是空?

iphone - 如何在当前 UITableViewController 上方添加一个 UIView

ios - performFetchWithCompletionHandler 永远不会被解雇