【问题标题】:Animate Background Color Of UIButton from WhiteColor to RedColor将 UIButton 的背景颜色从白色变为红色
【发布时间】:2015-02-03 14:32:44
【问题描述】:
我正在尝试制作一种颜色脉冲效果,使UIButton 的背景颜色具有动画效果,以使其不断地从一种颜色(WhiteColor)变为另一种颜色(RedColor)。
我正在尝试使用CABasicAnimation 更改不透明度,但我也无法使其与颜色一起使用。
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"];
我们将不胜感激每一个建议。
谢谢
【问题讨论】:
标签:
ios
objective-c
uibutton
cabasicanimation
【解决方案1】:
我找到了正确的方法。您需要记住 CGColor。这是我的错误。编译器在这里没有帮助。
目标 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"];
斯威夫特
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】:
我终于找到了解决方案:
我制作了一个两帧动画,其中我首先将背景颜色更改为红色,然后在第二帧中将其变为白色。我还可以操纵相对持续时间
[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 - 对按钮的任何更改进行动画处理(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)
})