Automatically adjust the height of a UITableViewCell based on its contents

I want to adjust the height of a cell depending on its contents. I know that UITableViewDelegate allows you to implement

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

but I don’t want to set the height hard. Is there a way to do this dynamically?

+3
source share
2 answers

You need to enter the code in this method, which calculates the height of the contents of the string. The exact code that you need to deliver depends entirely on what content you display.

, , , , , NSString sizeWithFont:.

+2

, , .

. , 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 height
    totalContentHeight += model.content.heightValue;        // content text view 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;
}
+1

Source: https://habr.com/ru/post/1769520/


All Articles