+2  A: 

Just a thought:

  • What if you had, say, six different types of cells each with their own identifier and a fixed height. One would be for a single-line cell, the other for a two-line cell, etc...

  • Every time your model changes, calculate the height for that row then find the nearest cell type that has height closest to what you need. Save that celltype identifier with the model. You can also store the fixed row height for that cell in the model so you can return it in the tableview:heightForRowAtIndexPath call (I wouldn't get too hung up on forcing it to calculate inside the cell class itself--technically it's not part of the cell drawing functionality and more something the tableview uses to decide which cell type to create).

  • At runtime, when asked to return a cell for that row all you need to do is create (or obtain from the cell cache) a cell with the celltype identifier, load the values and you're good to go.

If the cell height calculation is too slow, then you could pull the same trick the tableview cache does and do it only on-demand when the cell comes into view. At any given time, you would only have to do it for the cells in view, and then only for a single cell as it scrolls into view at either end.

Ramin
I've toyed with this idea in the past and couldn't get it to do exactly what I wanted. But maybe I can try again.
Jasarien
+5  A: 

Here's what I use. NSString has a method that will tell you the dimensions of a textbox based on the font information and the height/width constraints you give it.

- (CGFloat)tableView:(UITableView *)tableView 
heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *text;
CGSize s;
text = [self getTextForIndexPath:indexPath];
f = [UIFont systemFontOfSize:14];
s = [self getSizeOfText:text withFont:f];
    return s.height +11; //I put some padding on it.
    }

Then you write a method pull the text for this cell...

- (NSString *)getTextForIndexPath:(NSIndexPath *)indexPath{
NSString *sectionHeader = [self.tableSections objectAtIndex:[indexPath section]];
    NSString *sectionContent = [self.tableData objectForKey:sectionHeader];

    return sectionContent;
}

And this is to get the size of the text.

- (CGSize)getSizeOfText:(NSString *)text withFont:(UIFont *)font
{

    return [text sizeWithFont: font constrainedToSize:CGSizeMake(280, 500)];
}
John Leonard
Who downvoted this and why?
Jasarien
How can I use this method for only one cell in my grouped table View? I'd like to return the height of the cell based on the height of a textView inside the cell...
Matthew