Snips
Snips

Reputation: 6763

Efficiently determining the height of a custom variable size UITableViewCell

Firstly, I'm aware of, and regularly use,

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

...this question is a little more complex than that :-)

I have a custom UITableViewController that is data driven. Depending on the definition of the table at runtime, it pulls in a selection of custom cells (which are themselves separate custom UITableViewCell classes).

The custom cells are also data driven, and have heights that are only determined at run-time.

By doing some run-time logging, I see that UITableViewController calls heightFor... for all cells in the table before calling cellFor... for the visible cells.

This means that I'll effectively have to construct the cell once to determine the height, and then again to return the cell when requested.

Is it in any way possible to return a default value for the height via heightFor.. and then override this once the actual height is known?

Or are there any alternative solutions to avoid having to construct the cells twice?

Suggestions appreciated.

Upvotes: 1

Views: 261

Answers (2)

Snips
Snips

Reputation: 6763

OK, so there's no good solution here (i.e. you can't change the height of a cell once it's been created).

So, the solution I went with here is to call cellFor... from within heightFor..., which constructs the cell in order to get the height. I then record the height of that cell as a property, and obtain it from heightFor...

Having got the height, the cell is then automatically released (because it's not retained). Of course, shortly after, the UITableController will ask for the cell again, so it will be constructed twice, but that's how it goes...

Here's the code, and this works well.

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float height;

    UITableViewCell <CMyTableViewDelegate> *cell = (UITableViewCell <MyTableViewDelegate> *) [self tableView:tableView cellForRowAtIndexPath:indexPath];

    height = [cell getHeight];

    return height;
}

Hope that helps someone else out.

Upvotes: 1

wczekalski
wczekalski

Reputation: 745

No it's not possible. Think again about solution. Im going to give you a few pointerS.

  • Cache calculated height
  • Check performance of uitablebiewcell itself. Maybe it haS too many subviews.
  • Precalculate height if possible - do it before data source of table view asks you to do so, then return cached height

Upvotes: 0

Related Questions