Search code examples
iosobjective-cuitableviewheightforrowatindexpath

heightForRowAtIndexPath with custom cell and label


If I'm making a custom UITableViewCell and I need it to have a variable height depending on the length of the input (for instance, for a Twitter reader or something), how can I make this work?

I've found lots of other examples here that can set it for a the standard, non-custom cell, but my cell's main text label is smaller, etc., so when I try to use any of those methods on my cell, they give a variety of weird results (text overlapping the bottom of the cell, etc.)

Is there a standardized way of designing the cell (for example, how tall should I make it in Interface Builder?), and let's say my label was half the width of that cell.. how would I go about calculating the height the cell would need to be to display the string loaded into that label? Here's a method that I found here which works fine on the normal cell, but screws up custom ones with weird heights, overlapping text, etc: (I have absolutely NO idea what the 300 / 200000 do here, if anyone could explain that I'd be grateful, too!)

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGSize  textSize = {300.f, 200000.0f};
    CGSize  size = [[_quoteStringsFromPlist objectAtIndex: indexPath.row] sizeWithFont: [UIFont systemFontOfSize:12.0f] constrainedToSize: textSize lineBreakMode: NSLineBreakByWordWrapping];
    size.height += 5.0f;
    float result = MAX(size.height, 32.0f);
    return result;
}

Solution

  • Something like this should work.

    CGRect labelFrame = // enter default frame of the label here
    UIFont *labelFont = // enter label font here
    CGFloat labelBottomMargin = // enter the space between the bottom of the label and the bottom of the cell here
    
    CGSize  size = [labelString sizeWithFont:labelFont constrainedToSize:CGSizeMake(labelFrame.size.width, MAX_FLOAT)];
    size.height += labeFrame.origin.y;
    size.height += labelBottomMargin;
    size.height = MAX(size.height, 32.0f);
    return size.height;