I'm having trouble trying to get a custom UIView class to fade its background. I checked 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 backgroundColor CALayer?
So, I have a custom UIView where users can draw things. If what they draw is wrong, I want the background color to fade to red and then go back to white.
I have this custom method in a custom UIView called
- (void)indicateMistake;
When I call this method, I want it to perform 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 happens when I do this.
So, I tried a dumb 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, the work and the custom UIView are spinning.
Then, after reading more StackOverflow answers, I tried this:
[UIView animateWithDuration:3 animations:^{ [self setBackgroundColor: [UIColor redColor]]; } completion:^(BOOL finished) { [self setBackgroundColor: [UIColor whiteColor]]; }];
This immediately changes color from red and then back to white. Sometimes it’s so fast that sometimes I don’t see it happen. If I comment [self setBackgroundColor: [UIColor whiteColor]]; It will remain red. But there node is a gradual effect from white to red.
I have run out of ideas .. Any help would be appreciated!