objective-c – 如何根据NSString计算动态大小的UITableViewCells所需的高度

我有一个UITableView,它有自定义UITableViewCells,这是用户的评论.现在,我有115.0f高的单元格,但我希望根据评论的时间长度改变高度.如果评论超过三行,我希望用户能够选择单元格,并且要扩展单元格以显示整个评论.我一直在使用[UIView animateWithDuration:completion:方法来扩展单元格,但我不知道如何根据文本的长度来确定单元格的正确大小.有人可以帮我吗?这是一些代码:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    if (indexPath.row == 0)
    {
        return 480;
    }
    else
    {
        if (self.cellType == 0)
        {   
            return 115;
        }
        else
        {
            return 75;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row > 0)
    {
        NSIndexPath *path = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:path];
        if ([cell isKindOfClass:[CommentCell class]])
        {
            CommentCell *cell = (CommentCell *)[tableView cellForRowAtIndexPath:indexPath];
            UILabel *label = cell.commentBodyLabel;
            NSString *theText = label.text;
            CGSize constraintSize = CGSizeMake(label.frame.size.width, label.frame.size.height);
            CGSize labelSize = [theText sizeWithFont:label.font constrainedToSize:constraintSize lineBreakMode:label.lineBreakMode];
            CGFloat labelHeight = labelSize.height;
            int numLines = (int)(labelHeight/label.font.leading);
            NSLog(@"there are %i lines", numLines);
            NSLog(@"The text height is %f", labelHeight);
            if (numLines == 3)
            {
                //This is where I should expand the cell
            }
        }

最佳答案 看看
NSString UIKit Additions

您对sizeWithFont特别感兴趣:constrainedToSize:lineBreakMode:

将constrainedToSize属性的CGSize.width设置为单元格/标签区域的宽度.然后将CGSize.height设置为一个非常大的数字,可能是CGFLOAT_MAX.这个想法是你说的“嘿,这个标签必须适合一个静态宽度的区域,但它可以永久垂直.所以,告诉我这个标签实际上有多高,我给你的信息“.

NSString *comment = @"Some really long comment that does not fit in the standard cell size. This comment will be wrapped by word. Some more words to make this longer...";

CGSize renderedSize = [comment sizeWithFont:myFont constrainedToSize:CGSizeMake(kCellWidth, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];

renderedSize.height是你要返回的值(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

点赞