0

我正在努力解决如何在 uitableviewcell 中动态调整 uilabel 的大小,以及如何根据我放入标签的文本来调整表格单元格的高度。我想在表格视图单元格中完整显示一个字符串,所有单元格的字体大小始终相同。这似乎很标准,但我注意到 stackoverflow 上有很多讨论/辩论/不满。我开始使用这些帖子:

根据 JSON 文件中的内容文本调整带有 UILabel 的自定义单元格的大小(@Seya的回答) boundingRectWithSize for NSAttributedString 返回错误的大小(@JOM 的回答)

我尝试使用的功能是 Seya 所做的复制,几乎没有修改。但是,我看到尽管该函数为不同的单元格打印出不同的高度,但我所看到的只是每个标签 1 行文本,即使它们应该显示很多行。此外,奇怪的是来自一个单元格的文本似乎显示在另一个单元格的顶部 - 不确定这是否相关。

我的两个问题:(1)为什么我只看到第一行文字?(2) 为什么 UILabel/cell 没有根据我在日志中看到的不同高度调整大小(或者它们是否在调整大小但被问题 #1 掩盖)?

这是我正在使用的三个功能(这些以及 xib - xib 可能是问题吗?):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
JudgeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JudgeCell"];
    if(!cell)
    {
        [tableView registerNib:[UINib nibWithNibName:@"JudgeCell" bundle:nil] forCellReuseIdentifier:@"JudgeCell"];
        cell = [tableView dequeueReusableCellWithIdentifier:@"JudgeCell"];
    }

    cell.username.text = self.object.answerUser[indexPath.row];
    cell.answer.text = self.object.answerArray[indexPath.row];

    NSString *text = cell.answer.text;
    CGSize constraint = CGSizeMake(50, 20000.0f);
    CGSize size = [self frameForText:text sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:constraint];

    cell.username.frame = CGRectMake(10, 10, 50, size.height); //MAX(size.height, 14.0f));

    return cell;

}

-(CGSize)frameForText:(NSString*)text sizeWithFont:(UIFont*)font constrainedToSize:(CGSize)size  {

    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;

    NSDictionary * attributes = @{NSFontAttributeName:font,
                                  NSParagraphStyleAttributeName:paragraphStyle
                                  };


    CGRect textRect = [text boundingRectWithSize:size
                                         options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                      attributes:attributes
                                         context:nil];

    NSLog(@"size is %f ", textRect.size.height);
    return textRect.size;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    NSString *text = self.object.answerArray[indexPath.row];
    CGSize constraint = CGSizeMake(50, 20000.0f);
    CGSize size = [self frameForText:text sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:constraint];
    CGFloat height = size.height; //MAX(size.height, 14.0f);
    NSLog(@"size is %f AT INDEX %d", height, indexPath.row);
    return height + 20;
}

感谢您的任何建议!

4

1 回答 1

0

最后,我删除了关联的 nib 文件,不知何故,这似乎与本教程中的代码一起解决了问题(类似于我上面已经发布的内容):

http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/

请注意,本教程中的方法有时会被标记为已弃用。如果我找到更新的教程,我会发布。

于 2014-11-21T18:02:37.313 回答