在iOS中使用Swift3为UIButton设置'backgroundColor'的动画

问题描述:

我想为我的UIButtons的backgroundColor属性设置动画,但我不确定从哪里开始。我从来没有使用过Core Animation,我不确定我是否需要这么基本的东西?在iOS中使用Swift3为UIButton设置'backgroundColor'的动画

我风格使用类和看起来像这样的方法的按钮:

redTheme.swift

func makeRedButton() {  
     self.layer.backgroundColor = myCustomRedcolor 
    } 

您可以UIView Animation为以下做:

注意:只要不要忘记在执行动画之前清除背景,否则它将无法工作。那是因为动画需要一个起点和终点,起点是对红色的清晰颜色。或者将alpha 0转换为alpha 1或者反过来。

let button = UIButton(frame: CGRect(x: 0, y: 100, width: 50, height: 50)) 
button.layer.backgroundColor = UIColor.clear.cgColor 
self.view.addSubview(button) 

     func makeRedButton() { 

      UIView.animate(withDuration: 1.0) { 
       button.layer.backgroundColor = UIColor.red.cgColor 
      } 

     } 
+0

完美谢谢! – Brewski

出于某种原因,动画button.layer.backgroundColor 过零效果为我定制的UIButton所以我的动画阿尔法像这样:

func provideVisualFeedback(_ sender:UIButton!) 
{ 
    sender.backgroundColor = UIColor.whatever 
    sender.alpha = 0 
    UIView .animate(withDuration: 0.1, animations: { 
     sender.alpha = 1 
    }, completion: { completed in 
     if completed { 
      sender.backgroundColor = UIColor.white 
     } 
    }) 
} 

然后

@IBAction func buttonAction(_ sender:NumberPadButton!) 
{ 
    provideVisualFeedback(sender) 
    do your thing once animation was setup with the helper above