将UIButton的背景颜色从WhiteColoranimation到RedColor

我正在试图制作一种颜色脉冲效果animationUIButton背景颜色,使其从颜色(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"]; 

每一个build议,将不胜感激。 谢谢

我find了正确的方法。 你需要记住关于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") 

我终于find了解决办法:我做了一个两帧的animation,我首先将背景颜色改为红色,在第二帧中将其变成白色。 我也可以操纵相对的持续时间

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