The way Apple implements a UITableView is not intuitive for everyone, and it is easy to understand the meaning of heightForRowAtIndexPath: The main intention is that it is a quick and easy method that can be called for each row of the table quite often. This contrasts with cellForRowAtIndexPath: which is often slower and more intensive than memory, but only called for strings that really need to be displayed at any given time.
Why does Apple implement this? Part of the reason is that it is almost always cheaper (or maybe cheaper if you code it correctly) in order to calculate the height of the line than it should build and fill in the whole cell. Given that in many tables the height of each cell will be the same, it is often much cheaper. And another part of the reason is that iOS needs to know the size of the entire table: this allows you to create scrollbars and customize them as scrollbars, etc.
Thus, if each cell height is not the same, then when a UITableView is created and whenever you send it a reloadData message, the data source is sent to one heightForRowAtIndexPath message for each cell. Therefore, if your table has 30 cells, this message is sent 30 times. Say only six of the 30 cells are visible on the screen. In this case, when creating and sending the reloadData message, the UITableView will send one cellForRowAtIndexPath message to the visible line, that is, this message is sent six times.
Some people sometimes wonder how to calculate cell height without creating the views themselves . But usually it’s easy to do.
For example, if the height of the lines depends on the size, because they contain a different amount of text, you can use one of the sizeWithFont: methods in the corresponding line to perform the calculations. This is faster than creating a view and then measuring the result. Note that if you change the height of the cell, you will need to either reload the entire table (using reloadData - this will ask the delegate for each height, but only asks for visible cells) or selectively reload the rows in which the size is changed (which, in the last the time I checked also calls heightForRowAtIndexPath: on any line, but also does some scrolling for a good estimate).
See this question and perhaps also this one .
Obliquely Sep 09 '11 at 15:03 2011-09-09 15:03
source share