Search code examples
iosanimationuitableviewblockuibackgroundcolor

Animating UITableViewCell's backgroundColor in block animation


I'm trying to animate two table cells background colors from red back to the original color, white.

The following code is what I'm using. The problem is that it never shows the red color -- it simply animates from (original) white to (animated-to) white. I.e., if I change the color in the animation block, it will animate to that color.

[table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]].backgroundColor = [UIColor redColor];
[table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]].backgroundColor = [UIColor redColor];

[UIView animateWithDuration:0.8 delay:0.2 options:UIViewAnimationOptionCurveEaseInOut animations:^{
    [table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]].backgroundColor = [UIColor whiteColor];
    [table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]].backgroundColor = [UIColor whiteColor];
}
completion:^(BOOL finished) {

}];

The following code works as expected for the table's background, but that's not what I want:

table.backgroundColor = [UIColor redColor];

[UIView animateWithDuration:0.8 delay:0.2 options:UIViewAnimationOptionCurveEaseInOut animations:^{
    table.backgroundColor = [UIColor clearColor];
}
completion:^(BOOL finished) {

}];

So, why doesn't my cell background animate when my table background does?

For what it's worth, I have a bunch of other chained animations I perform on the table view right after this, but having commented those animations out, I still have this issue.


Solution

  • It looks like @Jason Coco is right. I can't do it (cleanly and quickly):

    From Apple:

    Note: If you want to change the background color of a cell (by setting the background color of a cell via the backgroundColor property declared by UIView) you must do it in the tableView:willDisplayCell:forRowAtIndexPath: method of the delegate and not in tableView:cellForRowAtIndexPath: of the data source. Changes to the background colors of cells in a group-style table view has an effect in iOS 3.0 that is different than previous versions of the operating system. It now affects the area inside the rounded rectangle instead of the area outside of it. Reference

    So if I really wanted to I'd have to set some variable, then call reloadData on the table or something similar.