views:

2481

answers:

3

I have a UITableView cell that is going to have a variable size depending on it's content (potentially several lines of text).

SInce it appears that heightForRowAtIndexPath is called before I layout the cell, I just guess the correct height by calling [NSString sizeWithFont] on my text string. Is there a better way to set the height after I've laid out the text in the cell and have an idea of exactly what size it should be?

+4  A: 

It's going to sound dumb, but ...uh... "layout your cell before you exit heightForRowAtIndexPath" ;)

Seriously, though -- the OS only ever calls this if it's going to be needed (as in: it's about to create the cell & display it on screen), so laying it out & getting ready to display is not wasted effort.

Note, you do not have to do your layout separately, logic-wise. Just make a call to your [self prepLayoutForCellAtIndex:index] within your heightForRowAtIndexPath routine.

If the data is static, you can create a height table and cache the info.

if (0 == heightTable[index]) {
    heightTable[index] = [self prepLayoutForCellAtIndex:index];
}
return (heightTable[index]);

Heck, even if the data changes, you can either recalculate the table value in the method that changes the data, or clear to 0 so it gets recalculated the next time it's needed.

Olie
+3  A: 

I use the following, usually:

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {
UITableViewCell *cell = [self tableView: tableView cellForRowAtIndexPath: indexPath];
return cell.bounds.size.height;

}

Note that I use this for tables where I pre-cache a bunch of rows ahead of time, not for those with a LOT of cells. However, for things like Settings tables, where there are just a few rows, but most likely very differently sized, it works well. For larger tables, I do something along the lines of what Olie suggested.

Ben Gottlieb
A: 

If you look at SMS.app as example, Apple saves the row height of the cell in the SMS.app sqlite database.

catlan