Change the background colour of UITableViewCell

In one of the IOS apps I am currently working on I been using a table view controller to display information for a core data database.  I was wanting to change the background colour of the UITableCell depending on a boolean variable in my manged objects.

Originally I tried setting this in the UITableView delegate method

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

After I quick test I realised that because the UITableViewCell is effectively recycled (de-cued and used again) this approach was not going to work.

After a little more reading I found the UITableView delegate method

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

This is what you need to use if you want to change a cell that is displaying a specific row (index path) in your table.

Here is an example of the code I used in my app:


-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
    MonkeyManagedObject *monkey = [self.fetchedResultsController objectAtIndexPath:indexPath];
    if ([monkey.hasBanana isEqualToNumber:[NSNumber numberWithBool:YES]] ) {
        cell.backgroundColor = [UIColor redColor];
    } else {
        cell.backgroundColor = [UIColor whiteColor];        

In my code I am using a NSFetchedResultsController to populate my table view also because the Boolean type in a managed object is actually an NSNumber you need to use the NSNumber class method:

[NSNumber numberWithBool:YES]

Leave a Reply

Your email address will not be published. Required fields are marked *