Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating alternating colored UITableViewCells when rows gets reordered or deleted

I'm having a UITableView with alternating colored UITableViewCells. And the table can be edited: rows can be reordered and deleted. How do I update the cells alternating background color, when the rows get reordered or deleted?

I'm using this to draw the alternating colored cells:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([indexPath row] % 2) {
        // even row
        cell.backgroundColor = evenColor;
    } else {
        // odd row
        cell.backgroundColor = oddColor;
    }
}

But this method is not being called when a row gets reordered or deleted. And I can't call [tableView reloadData] from the following method, because it crashes the app in an infinite loop:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    // Move the object in the array
    id object = [[self.list objectAtIndex:[fromIndexPath row]] retain];
    [self.list removeObjectAtIndex:[fromIndexPath row]];
    [self.list insertObject:object atIndex:[toIndexPath row]];
    [object release];

    // Update the table ???
    [tableView reloadData]; // Crashes the app in an infinite loop!! 
}

Does anybody have a pointer or a best practices solution to deal with the issue of reordering alternating colored cells?

Thanks

like image 898
Dirk van Oosterbosch Avatar asked Aug 23 '09 22:08

Dirk van Oosterbosch


1 Answers

Used a delayed call to perform the reload if you can't call from that method:

[tableView performSelector:@selector(reloadData) withObject:nil afterDelay:0.0f];

It waits until after your current method is finished before it calls reload.

like image 135
Kendall Helmstetter Gelner Avatar answered Oct 04 '22 17:10

Kendall Helmstetter Gelner