Jonathan.
Jonathan.

Reputation: 55554

UITableViewDelegate methods

Here is an xcode project that I just did to ask this question:

http://www.mediafire.com/?z26ufsfhby62br9

Open the log and run it. You will find that it outputs display: x and create: x where x is a number 0 to 49 and corresponds to the cell of the same number. It should only output to 22 before any scrolling is performed as Apple are always boasting that their tableviews are loaded as needed.

It basically shows that tableView:willDisplayCell:forRowAtIndexPath: and tableView:cellForRowAtIndexPath: are fired for each cell pretty much as soon as the tableview appears, why is this?

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"create: %i", indexPath.row);
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                       reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    cell.textLabel.text = [NSString stringWithFormat:@"%i", indexPath.row];
    return cell;
}

- (void) tableView:(UITableView *)tableView 
   willDisplayCell:(UITableViewCell *)cell 
 forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"display: %i", indexPath.row);   
}

Why are the above meothds called just after the tableView loads (and just before each cell appears)? Surely they should be called just before each cell appears only?

Upvotes: 0

Views: 1345

Answers (2)

Justin Spahr-Summers
Justin Spahr-Summers

Reputation: 16973

If your table view is reloading before it actually fully displays, that could cause the behavior you're seeing. Then the cells would get initialized, prepared for display, but then all of that would be lost (before even shown on screen) as the table is reloaded.

Upvotes: 0

KingofBliss
KingofBliss

Reputation: 15115

These are the default delegate methods.. This will be be called for each cell everytime.

You use willDisplayCell:forRowAtIndexPath: to configure things like font and text color. In the newer version of the iPhone, with certain table configurations, if you configure things like the label text color in the tableView:cellForRowAtIndexPath: method, your changes will be lost at some point before the cell is actually displayed. Here you can do things like change the label's color, adjust background highlighting, such things as these.

Upvotes: 1

Related Questions