Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to determine the right size for a UITableViewCell?

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?

like image 362
drewh Avatar asked Feb 04 '23 12:02

drewh


1 Answers

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.

like image 184
Olie Avatar answered Feb 06 '23 03:02

Olie