ios - 根据文本高度设置 UITableViewCell 高度和单元格的文本标签

标签 ios uitableview height label uilabel

我已按照我在 stackoverflow 上找到的说明来修复以下问题,但没有任何效果。下面是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *CellIdentifier = @"DoCCell";
DoCCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[DoCCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...

CGSize constraintSize = CGSizeMake(cell.infoLabel.frame.size.width, MAXFLOAT);
CGSize labelSize = [_content[[indexPath row] * 2] sizeWithFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:12.0f]
                                             constrainedToSize:constraintSize
                                                 lineBreakMode:NSLineBreakByWordWrapping];
CGRect frame = CGRectMake (cell.infoLabel.frame.origin.x, cell.infoLabel.frame.origin.y, labelSize.width, labelSize.height);
[cell.infoLabel setFrame:frame];

cell.infoLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.infoLabel.numberOfLines = 10;

_font = cell.infoLabel.font;
cell.infoLabel.text = _content[[indexPath row] * 2];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);

CGSize size = [_content[[indexPath row] * 2] sizeWithFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:12.0f]
               constrainedToSize:constraintSize
                   lineBreakMode:NSLineBreakByWordWrapping];
return size.height + 30.0;
}

但是当我运行代码时,单元格的高度会适当更改,而标签大小则不会。

该单元格是自定义单元格,我已通过 .xib 文件添加了标签。我尝试手动拉伸(stretch)标签,该标签可以显示所有文本,因此问题不在于标签的包装。我还测试了 cell.infoLabel.frame.size.height ,就值而言,高度值确实随着单元格的高度而变化,但它不会这样显示。我做错了什么?

最佳答案

我认为问题可能在于调整 UILabel 实例中文本的垂直对齐方式。

我认为你应该在 cellForRowAtIndexPath 中执行以下操作:

cell.infoLabel.text = _content[[indexPath row] * 2];
cell.infoLabel.numberOfLines = 0;
[cell.infoLabel sizeToFit];

有关它的更多详细信息可以在以下链接中找到:Vertical Alignment of UILabel Text

希望对您有所帮助! :)

关于ios - 根据文本高度设置 UITableViewCell 高度和单元格的文本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17865962/

相关文章:

ios - 如何在 SwiftUI 中为文本中的子字符串加下划线?

iphone - 在UITableView内部实现动态增长的TextView

javascript - jquery jScrollPane 视口(viewport)太小

ios - 通过其他按钮更改按钮上的图像

iphone - iOS Keychain 偶尔会返回空字符串

ios - iPhone 和 iPad 之间的不同行为

ios - 如何知道是否使用 MGSwipeTableCell 删除了所有单元格

ios - 调整 UITableView 的大小以适应内容

css - Bootstrap 网格列高度 100%

javascript - 使iframe根据内容自动调整高度而不使用滚动条?