title: How can I do variable height table cells on the iPhone properly?
body: <p>My app needs to have variable height table cells (as in each table cell differs in height, not that each cell needs to be able to resize itself).</p>
  
  <p>I have a solution that currently works, but it's kludgy and slow.</p>
  
  <p>My Current Solution:</p>
  
  <p>Before the table cells are rendered, I calculate how high each cell needs to be by calling sizing methods such as <code>-sizeWithFont:constrainedToSize:</code> on its data. I then add up the heights, allow for some padding and store the result with the data.</p>
  
  <p>Then when my UITableViewDelegate receives the <code>-tableview:heightForRowAtIndexPath:</code> I work out which item will be rendered for that cell and return the height that I calculated previously.</p>
  
  <p>As I said, this works, but calling <code>-sizeWithFont:constrainedToSize:</code> is very slow when you're doing it for hundreds of items sequentially, and I feel it can be done better.</p>
  
  <p>So for this to work, I had to maintain two parts of code - one that would calculate the cell heights, and one that would actually draw the cells when the time comes.</p>
  
  <p>If anything about the model item changed, I had to update both of these chunks of code, and now and again they still don't even match up perfectly, sometimes resulting in table cells that are slightly too small for a given item, or too large.</p>
  
  <p>My Proposed Solution:</p>
  
  <p>So I want to do away with the precalculating the cell height. A) because it breaks the MVC paradigm and B) because it's slow.</p>
  
  <p>So my cell draws itself, and as a result, ends up with the correct cell height. My problem is that I have no way of telling the table view the height of the cell before its drawn - by which time its too late.</p>
  
  <p>I tried calling <code>-cellForRowAtIndexPath:</code> from within <code>-tableView:heightForRowAtIndexPath:</code> but this gets stuck in an infinite loop, since the first calls the second at some point, and vice versa (at least this is what I saw when I tried it).</p>
  
  <p>So that option is out of the question.</p>
  
  <p>If I don't specify a size in the height for row delegate method, then the table view goes screwwy. The cells are the perfect height, but their x position is that of cells of fixed heights.</p>
  
  <p><a href="http://jamsoftonline.com/images/messed_table_cells.png">Messed Table Cells http://jamsoftonline.com/images/messed_table_cells.png</a></p>
  
  <p>Notice how the bottom cell is the correct size - it's just overlapping the previous cell, and the previous cell overlaps its previous, and so on and so forth.</p>
  
  <p>Also using this method, while scrolling there is some artifacting occurring which I think may be related to the reuse identifier for the cells.</p>
  
  <p>So any help here would be gratefully appreciated.</p>