Animate Background Color Of UIButton from WhiteCol

2020-07-16 08:58发布

问题:

I'm trying to making a kind of color pulse effect animating background color of a UIButton to make it change continously from a color (WhiteColor) to another one (RedColor). I'm trying to use CABasicAnimation for changing Opacity but I can't make it work with color too.

    CABasicAnimation *theAnimation;

    theAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"];
    theAnimation.duration=1.0;
    theAnimation.repeatCount=HUGE_VALF;
    theAnimation.autoreverses=YES;
    theAnimation.fromValue=[NSNumber numberWithFloat:1.0];
    theAnimation.toValue=[NSNumber numberWithFloat:0.0];
    [BigButton.layer addAnimation:theAnimation forKey:@"animateOpacity"];

Every suggestion would be appreciated. Thanks

回答1:

I found the right way. You need to remember about CGColor. This was my mistake. Compiler didn't help here.

Objective C

CABasicAnimation *theAnimation=[CABasicAnimation animationWithKeyPath:@"backgroundColor"];
theAnimation.duration=1.0;
theAnimation.repeatCount=HUGE_VALF;
theAnimation.autoreverses=YES;
theAnimation.fromValue= [[UIColor redColor] CGColor];
theAnimation.toValue= [[UIColor blueColor] CGColor];
[BigButton.layer addAnimation:theAnimation forKey:@"ColorPulse"];

Swift

let colorAnimation = CABasicAnimation(keyPath: "backgroundColor")
colorAnimation.fromValue = UIColor.redColor().CGColor
colorAnimation.toValue = UIColor.blueColor().CGColor
colorAnimation.duration = 1
colorAnimation.autoreverses = true
colorAnimation.repeatCount = FLT_MAX
self.layer.addAnimation(colorAnimation, forKey: "ColorPulse")


回答2:

I finally found out solution: I made a two frames animation in which I first change background color to Red and in the second frame I turn it white. I can also manipulate relative durations

    [UIView animateKeyframesWithDuration:2.0 delay:0.0 options:UIViewKeyframeAnimationOptionAutoreverse | UIViewKeyframeAnimationOptionRepeat animations:^{
        [UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:0.5 animations:^{
            someView.backgroundColor = [UIColor redColor];
        }];
        [UIView addKeyframeWithRelativeStartTime:0.5 relativeDuration:0.5 animations:^{
            someView.backgroundColor = [UIColor whiteColor];
        }];
    } completion:nil];


回答3:

Swift 4 - Animate any change on a button (backgroundColor, title, titleColor):

UIView.transition(with: yourButton, duration: 0.3, options: .curveEaseInOut, animations: {
  self.yourButton.backgroundColor = UIColor.red
  self.yourButton.setTitle("new title", for: .normal)
  self.yourButton.setTitleColor(.white, for: .normal)
})