ios - 表格 View 中动态单元格高度中的标签未正确显示文本

标签 ios objective-c swift uitableview row-height

我试图让我的表格 View 单元格根据单元格内的内容调整它们的高度。

它似乎可以工作,因为单元格具有不同的高度,但我无法正确显示文本。

TableView 和原型(prototype)单元格是使用 Storyboard创建的,我有一个自定义单元格类链接到我的原型(prototype)单元格。在我的原型(prototype)单元中,我有三个标签;标题标签、日期标签和具有动态文本数据的标签。在 Storyboard的属性检查器中,动态文本数据标签行号设置为 0,换行符设置为“自动换行”。

当我运行应用程序时,单元格高度都不同,因此我假设索引路径处行的高度有效:

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Text data
    NSDictionary *cellOutputDict = [newsDataArray objectAtIndex:indexPath.row];
    NSString *text = [NSString stringWithFormat:@"%@", [cellOutputDict objectForKey:@"text"]];

    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:nil];

    CGFloat width = 280;
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    CGSize size = rect.size;

    return size.height + 2 * 20; // size.height plus 2 times the desired margin
}

这是我在索引路径处的行单元格:

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

    // If the cell doesn't exists create it
    if (cell == nil) {
        cell = [[NewsCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    // Configure the cell...

    // Text data
    NSDictionary *cellOutputDict = [newsDataArray objectAtIndex:indexPath.row];

    cell.titleLabel.text = [NSString stringWithFormat:@"%@", [cellOutputDict objectForKey:@"title"]];
    cell.dateLabel.text = [NSString stringWithFormat:@"%@", [cellOutputDict objectForKey:@"date"]];
    cell.newsTextLabel.text = [NSString stringWithFormat:@"%@", [cellOutputDict objectForKey:@"text"]];

    return cell;
}

打印出动态文本数据的cell.newsTextLabel.text显示在单元格中,但只显示第一行。

我已经尝试了一些为 iOS 6.1 显示动态单元格高度的示例,它们工作正常,但我无法在 iOS 7+ 上工作

所以我希望有人可以帮助解决这个问题并帮助我弄清楚我做错了什么。

enter image description here

最佳答案

要使标签随单元格一起扩展,您应该给它一个约束,将其绑定(bind)到上方和下方的 View ——在您的情况下,这看起来像是对单元格底部的约束,一个是对标签的约束(与“标题...”)在它上面。

关于ios - 表格 View 中动态单元格高度中的标签未正确显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20426875/

相关文章:

ios - 如何使用 swift 2.0 在嵌套字典数组 JSON 响应集合中移动

ios - 在 iPhone 上创建本地通知

ios - 在 Swift 中以编程方式将 View 添加到 stackview

objective-c - iOS:UIPickerView 默认尺寸

objective-c - subscriberCellularProvider 在 iOS 12.0 中被弃用

ios - 如何在 Objective-C 中设置 Http header 字段?

iphone - MPMoviePlayerViewController 立即关闭

Swift:类类型没有成员 <var>

ios - 调用了 editActionsForRowAt IndexPath 但未显示 EDIT 和 DELETE

ios - 收藏 View 在闪烁后不显示任何项目