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

Animate the 'backgroundColor' for a UIButton in iOS using Swift3

我想为我的 UIButtons 的 backgroundColor 属性 设置动画,但我不确定从哪里开始。我从未使用过 Core Animation,我什至不确定我是否需要它来做如此基本的事情?

我使用 class 和如下所示的方法设置按钮样式:

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
            }

        }

出于某种原因动画 button.layer.backgroundColor 对我的自定义 uibutton 的影响为零,因此我像这样设置 alpha 动画:

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

Swift 4 - 一种简单的方法来动画化您的 UIButton 或任何其他 UIView:

上的任何更改
UIView.transition(with: button, duration: 0.3, options: .curveEaseInOut, animations: {
  self.button.backgroundColor = .red
  self.button.setTitle("ERROR", for: .normal)
  self.button.setTitleColor(.white, for: .normal)
})