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

标签 ios objective-c iphone uitableview

我需要能够调整 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 ... :-)

希望这会有所帮助!

关于ios - 根据文本量更改 UITableViewCell 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9827126/

相关文章:

ios - iPad 模拟器正常但 iPad 在使用 WKWebview 上传图像时崩溃应用程序

ios - iOS WebApp 的 FB.login 中断流程

objective-c - NSData initWithContentsOfURL : does not return the original allocation?

iphone - 是否可以通过编程将 iPhone 静音?

ios - 后台线程更新变量并导致索引越界 swift ios

iOS:动态更新启动屏幕

iphone - 将 NSTimeInterval 转换为国际通用的字符串的正确方法是什么?

ios - 卸载iOS应用程序时是否删除了 Realm 文件

iphone - 应用程序并不总是在主视图中启动

javascript - 居中输入字段 - 问题