This general topic has been asked here multiple times: how to render UITableViewCells with varying amount of text and thus varying height. The canonical answer is: you calculate the height in table view controller delegate in heightForRowAtIndexPath using sizeWithFont:constrainedToSize:lineBreakMode:. Later, the cell gets drawn, and you use something like [label sizeToFit] if needed, and all works like magic.

My problem: I am getting wrapping for some cells because sizeWithFont: returns different dimensions from actual drawing.

A specific example:

The text is this: "People forget that @BillGates had a sexy 1/4-inch thick slate back in 1993 from NEC. Whatever happens this week will NOT be about hardware!"

CGSize theSize = [text sizeWithFont:[UIFont systemFontOfSize:17.0f] constrainedToSize:CGSizeMake(310.0f, FLT_MAX) lineBreakMode:UILineBreakModeWordWrap];
NSLog(@"calculated size for %@: %f, %f",text, theSize.width, theSize.height);

This returns: 306.000000, 84.000000. (I.e 4 rows with 17px font and 4px linespacing, 21px leading.) Good.

However, later when actually drawing the cell:

label = (UILabel *)[cell viewWithTag:3];
label.text = [NSString stringWithFormat:@"%@", text];
label.lineBreakMode = UILineBreakModeWordWrap;
label.font = [UIFont systemFontOfSize:17.0f];
CGSize labelSize;   
labelSize = label.frame.size;
NSLog(@"label size before resizing: %f, %f", labelSize.width, labelSize.height);
[label sizeToFit];
labelSize = label.frame.size;
NSLog(@"label size after resizing: %f, %f for text %@", labelSize.width, labelSize.height,text);

(UILabel is loaded as part of UITableViewCell from NIB. In IB I set it to 310px wide.)

This should return exactly the same size as above. Instead, I get 281.000000, 105.000000 as the dimensions after sizeToFit call. It is now 5 lines at drawing time instead of 4, and the text spills over, I see the spillover in the UI.

Edit
Report