views:

32

answers:

1

In a table view I use custom UITableViewCells with dynamic height. The layout algorithm is complicated since there are not only dynamic text blocks but also images with different height. When the appropriate heightForRowAtIndexPath is called the teble view cell has not been rendered do far. Do i have to calculate the height twice? Once for heightForRowAtIndexPath and onece for cellForRowAtIndexPath? Or is there a Pattern how to combine that?

A: 

You don't have to write the computation code twice. You can do all the hard work in cellForRowAtIndexPath: and then use the result to get the height in the height method. For example, your height method could look like this (using some short names to help it fit):

// I usually use descriptive variable names, but they won't fit on one line here.
- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)i {
  UITableViewCell *cell = [self tableView:t cellForRowAtIndexPath:i];
  return cell.frame.size.height;
}

The bad part of this code is that this method will get called for every row in your table before the table is first displayed (the OS does this), which may appear as lag in your app. If your heights change over time (per row), then it would be good to have some faster way to compute the height, which, yes, is a lot more work. However, if your row heights are always the same (per row) over time, then you can just cache the heights.

Reference with some caching code you can use for this: http://bynomial.com/blog/?p=90

Tyler