In such situations, I usually pre-compute the heights of all my rows, store them in an array, and then simply return those heights to heightForRowAtIndexPath . Thus, the table view knows the height of each cell, and the cells must match this height even after reuse. I donβt know how to get the cell height to be calculated before looking for when the cell will be visible and reboot, which seems too expensive.
Update : code example:
I have a method called - (void)calculateHeights that does the same calculations as in heightForRowAtIndexPath , but stores the result in my heights_ ivar mutable array:
- (void)calculateHeights { [heights_ removeAllObjects] for (Widget *myWidget in modelWidgetArray) { NSString* cellText; // code to load cellText dynamically is snipped off UIFont *cellFont = [UIFont fontWithName:@"Georgia" size:14.0]; CGSize constraintSize = CGSizeMake(230.0f, MAXFLOAT); CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; [heights_ addObject:[NSNumber numberWithFloat:labelSize.height + 20.0f]]; } }
And then in heightForRowAtIndexPath , given the view of the table from 1 section:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return [heights_ objectAtIndex:[indexPath row]]; }
If there are several sections in your table view, you will need to do some math to convert to the one-dimensional array heights_ and vice versa. In addition, every time you -reloadData , you also need -calculateHeights .
source share