Animate Background Color Of UIButton from WhiteColor to RedColor

守給你的承諾、 提交于 2019-12-04 07:10:31

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")

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];

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)
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!