Auto adjust the UITableViewCell height depending on its contents

2 Solutions Collect From Internet About “Auto adjust the UITableViewCell height depending on its contents”

You have to enter some code into that method that calculates the height of the row content. Exactly what code you need to put depends entirely on what kind of content you’re displaying.

For example, if you’re displaying text content that may wrap across multiple lines, you’re probably going to end up using one of NSString’s sizeWithFont: family of methods.

If you want your rows to have different heights, you have to calculate every row’s height.

I’ve met such a problem. I calculated the heights of rows according to contents parsed from a json string. here’s what i did.

- (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;