Ben Packard
Ben Packard

Reputation: 26476

Background color of a UITableViewCell

I'm using a basic table view cell, set up in IB. The only customization I apply is in cellForRowAtIndexPath, where I simply set the background color of the cell's label (not the color of the cell itself).

    [[cell textLabel] setBackgroundColor:[UIColor yellowColor]];

When the table is first drawn, the background color is not applied. As I scroll down, it is applied to new cells as they are drawn. Similarly, if I scroll back up, the top cells are re-drawn with the correct background color.

What is the explanation behind this?

enter image description here enter image description here

Edit - here's my cellForRowAtIndexPath, and the set up in IB:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
ItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ItemCell2"];
[[cell textLabel] setBackgroundColor:[UIColor yellowColor]];            
return cell;

}

enter image description here

Upvotes: 1

Views: 1449

Answers (1)

Tark
Tark

Reputation: 5173

you have to use

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

from the docs:

A table view sends this message to its delegate just before it uses cell to draw a row, thereby permitting the delegate to customize the cell object before it is displayed. This method gives the delegate a chance to override state-based properties set earlier by the table view, such as selection and background color.

Upvotes: 5

Related Questions