How can I change the background color of a UITableViewCell dynamically?

I have a variable that is going to keep track of how many cells need to be colored. So if that variable is 3, then the top three cells backgroundcolor will change. How can I do this?

I know I need to update this in

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

But how can I ensure the top cells have a different background color based on my variable?


The indexPath parameter is your starting point. If coloredCells is an integer that holds the number of cells you are coloring, your method would include something like

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    // fetch or create the cell, first
    UITableViewCell *cell = // ... 

    // then set it up
    if(indexPath.row < self.coloredCells) {
        cell.contentView.backgroundColor = [UIColor redColor];
    } else {
        cell.contentView.backgroundColor = [UIColor whiteColor];

    // perform rest of cell setup
    // ...

    return cell;

Now, if you adjust the value of coloredCells, you'll need to inform the table view that some of its views have changed. The laziest way to do that is to reload the whole table:

// elsewhere...
self.coloredCells = 4;
[self.tableView reloadData];

Or you can take a little more effort to reload just the cells that have colored backgrounds:

self.coloredCells = newColoredCount;
NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:newColoredCount];
for(int i = 0; i < newColoredCount; i++) {
    [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
[self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];

Need Your Help

Rake aborted! Can't convert Hash into String?

ruby-on-rails ruby

How do I better debug this message? The trace shows 3 lines from one of my files - application.rb:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.