I'm having trouble trying to get a custom UIView class to fade it's background. I've checked out the following StackOverflow questions but they don't seem to work for me.
Fade background-color from one color to another in a UIView
How do you explicitly animate a CALayer's backgroundColor?
So I have a custom UIView where users can draw things. If what they draw is incorrect, I want to make the background color fade to red then back to white.
I have this custom method in the custom UIView called
- (void)indicateMistake;
When I call that method I want it to perform the background color animation, so i have this in the method:
CABasicAnimation* fade = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
fade.fromValue = (id)[UIColor whiteColor].CGColor;
fade.toValue = (id)[UIColor redColor].CGColor;
[fade setDuration:3];
[self.layer addAnimation:fade forKey:@"fadeAnimation"];
But nothing seems to happen when I do that.
So then I tried a silly rotation animation to see if it even works:
CABasicAnimation* rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
rotate.toValue = [NSNumber numberWithInt:M_PI];
[rotate setDuration:1];
[self.layer addAnimation:rotate forKey:@"rotateAnimation"];
For some reason that works and the custom UIView rotates.
Then reading more StackOverflow answers I tried this:
[UIView animateWithDuration:3 animations:^{
[self setBackgroundColor: [UIColor redColor]];
} completion:^(BOOL finished) {
[self setBackgroundColor: [UIColor whiteColor]];
}];
That changes the color from red then back to white immediately. Sometimes It's so fast I sometimes can't see it happen. If i comment out the [self setBackgroundColor: [UIColor whiteColor]];
it stays red. But There's node gradual white to red effect.
I've ran out of ideas.. Any help would be appreciated!