views:

669

answers:

3

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

A: 

[tableView reloadData] will get your table backgrounds back in the swing of things. Your other option is to swap the background colors of the all visible cells from the indexPath of the lower index in the move on up to the highest in visibleCells.

uprise
+1  A: 

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.

Kendall Helmstetter Gelner
Thanks! That does the trick.
Dirk van Oosterbosch
A: 

Reload is too heavyweight; I've written AltTableViewController that just changes background color of cells and it should work faster.

dimzzy