title: Calculating multiline text height for UILabel/UITableViewCell: different results when calculating vs actual drawing
body: <p>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.</p>
  
  <p>My problem: I am getting wrapping for some cells because sizeWithFont: returns different dimensions from actual drawing.</p>
  
  <p>A specific example:</p>
  
  <p>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!"</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>This returns: 306.000000, 84.000000. (I.e 4 rows with 17px font and 4px linespacing, 21px leading.) Good.</p>
  
  <p>However, later when actually drawing the cell:</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>(UILabel is loaded as part of UITableViewCell from NIB. In IB I set it to 310px wide.)</p>
  
  <p>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.</p>
  
  <p>So, for the same text, I am getting two different dimensions calculated, and can't figure it out. Is it something about UILabel? Does it have some inner margins? This keeps happening for some texts but not others, and I have not traced it to something particular about the strings; seems random. <a href="https://stackoverflow.com/questions/1526910/uilabel-inside-custom-uitableviewcell-not-drawing-at-the-correct-size">This topic</a> highlights that there are two processing passes: calculating height vs actual drawing. This is consistent with what I'm seeing. But I don't understand what exactly is going on or how to fix it.</p>
  
  <p>The question: why am I seeing two different calculated sizes, and how do I fix it?</p>