Greg Greg - 5 months ago 35
iOS Question

heightForRowAtIndexPath being called for all rows & how many rows in a UITableView before performance issues?

I thought I had read that for a

UITableView
that
heightForRowAtIndexPath
doesn't get called on all rows, but only on the ones that will be visible. This isn't what I'm seeing however. I'm seeing hundreds of calls to
heightForRowAtIndexPath
for the simple situation of the orientation being changed of the iPhone for example.

So I'm assuming here therefore that for a
UITableView
with
heightForRowAtIndexPath
implemented, it does (i.e.
heightForRowAtIndexPath
) get called for all rows (not just the visible ones)...let me know if this isn't quite correct.

QUESTION: Given the above, how many rows in a
UITableView
(where
heightForRowAtIndexPath
is implemented) can you have before performance issues occur typically?


Is there a way around the performance issues? i.e. set a nominal/standard height for each row and not implement
heightForRowAtIndexPath
, but then correctly set each row height only when it is displayed and set it correctly here...but which method would one do this in?

Answer

Have a look at the discussion section in the tableView:heightForRowAtIndexPath: documentation

The method allows the delegate to specify rows with varying heights. If this method is implemented, the value it returns overrides the value specified for the rowHeight property of UITableView for the given row.

There are performance implications to using tableView:heightForRowAtIndexPath: instead of the rowHeight property. Every time a table view is displayed, it calls tableView:heightForRowAtIndexPath: on the delegate for each of its rows, which can result in a significant performance problem with table views having a large number of rows (approximately 1000 or more).

So you should use the rowHeight property of the UITableView. If you need different heights you are out of luck because you have to use tableView:heightForRowAtIndexPath:.

AFAIK there is no way to change the row height at display.
The tableview has to know the correct size before, otherewise there would be ugly position shifts all the time.