Why heightForRowAtIndexPath: come before cellForRowAtIndexPath :?

Almost every time I write an application for a client, I have to implement some kind of β€œhack” in order to get UITableViewCellin order to dynamically become the right height. Depending on the content of cells, this may vary depending on complexity.

I usually end up with code that formats the cell twice, once in heightForRowAtIndexPath:, and then back in cellForRowAtIndexPath:. Then I use an array or dictionary to store the height or formatted cell object.

I probably wrote and rewrote this code 20 times in the last 2 years. Why did Apple implement it in that order? It would be much simpler to adjust the cells, and THEN to set the height either at cellForRowAtIndexPath:or soon after heightForRowAtIndexPath:.

Is there a good reason for the existing order? Is there a better way to handle this?

+4
source share
2 answers

Best guess: UITableViewmust know the total height of all cells so that she can know the percentage of scroll for the scroll bar and other needs.

+6
source

Actually, in iOS 7 it should not work this way. Now you can set the approximate height for your lines and calculate the real height of each line only when this line is really needed. (And I suppose this happens precisely because people filed complaints identical to yours: β€œWhy should I do this twice?”)

, memoize , ( , , ):

- (void)viewDidLoad {
    [super viewDidLoad];

    // create empty "sparse array" of heights, for later
    NSMutableArray* heights = [NSMutableArray new];
    for (int i = 0; i < self.modeldata.count; i++)
        [heights addObject: [NSNull null]];
    self.heights = heights;

    self.tableView.estimatedRowHeight = 40; // new iOS 7 feature
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    int ix = indexPath.row;
    if ([NSNull null] == self.heights[ix]) {
        h = // calculate _real_ height here, on demand
        self.heights[ix] = @(h);
    }
    return [self.heights[ix] floatValue];
}

, . , , , , , .

, , dequeueReusableCellWithIdentifier:forIndexPath:, . ( dequeueReusableCellWithIdentifier:).

+3

Source: https://habr.com/ru/post/1525146/


All Articles