Iphone 根据UITableViewCell的内容自动调整其高度

Iphone 根据UITableViewCell的内容自动调整其高度,iphone,objective-c,uitableview,Iphone,Objective C,Uitableview,我想根据单元格的内容调整单元格的高度。我知道UITableViewDelegate允许您实现 - (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath { return someHeight; } 但我不想硬编码高度。有没有一种方法可以动态执行此操作?您必须在计算行内容高度的方法中输入一些代码。确切地说,您需要放置什

我想根据单元格的内容调整单元格的高度。我知道UITableViewDelegate允许您实现

- (CGFloat) tableView: (UITableView *) tableView 
              heightForRowAtIndexPath: (NSIndexPath *) indexPath {
    return someHeight;
}

但我不想硬编码高度。有没有一种方法可以动态执行此操作?

您必须在计算行内容高度的方法中输入一些代码。确切地说,您需要放置什么代码完全取决于您显示的内容类型


例如,如果您显示的文本内容可能会跨多行换行,则可能会使用NSString的
sizeWithFont:
方法系列之一。

如果希望行具有不同的高度,则必须计算每行的高度

我遇到过这样的问题。我根据从json字符串解析的内容计算了行的高度。这就是我所做的

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    // parse json
    id qWeiboContent = [self.array objectAtIndex:indexPath.row];

    float totalContentHeight;
    QWeiboContentModel *model = [self getQWeiboContentFromJSON:qWeiboContent];
    QWeiboContentModel *subModel = nil;

    totalContentHeight += model.forOrComment.heightValue;   // comment text view's height
    totalContentHeight += model.content.heightValue;        // content text view's height
    totalContentHeight += 21 * 2;                           // 21 is height of a label
    totalContentHeight += model.imageUrl.heightValue;
    totalContentHeight += CELL_CONTENT_MARGIN;

    if ([model.type isEqualToString:REPOSTED]) {

        id qWeiboSource = [qWeiboContent objectForKey:@"source"];
        subModel = [self getQWeiboContentFromJSON:qWeiboSource];
        model.source = subModel;

        totalContentHeight += subModel.forOrComment.heightValue;    
        totalContentHeight += subModel.content.heightValue;         
        totalContentHeight += 21 * 2;                              
        totalContentHeight += subModel.imageUrl.heightValue;
        totalContentHeight += CELL_CONTENT_MARGIN;
    }

    if (self.arrayQQWeibo == nil) {

        self.arrayQQWeibo = [[NSMutableArray alloc]init];
    }
    [self.arrayQQWeibo addObject:model];

    return totalContentHeight;
}

当然有。但如何做到这一点在很大程度上取决于你想做什么。如果要根据图像更改单元格高度,这非常简单;如果要使单元格高度依赖于字符串中的换行符,则需要进行更多计算。那么你想做什么呢?我有一个自定义单元格,它接受UILabel或UIImageView。正如您所说,根据图像的高度调整高度非常简单。但是,我如何知道UILabel需要多少空间呢?