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

Bre*_*ski 3 core-animation ios swift3

我想动画我的UIButtons的backgroundColor属性,但我不知道从哪里开始.我从来没有使用过核心动画,我不确定我是否需要它来做一些如此基本的东西?

我使用类和方法来设置按钮样式,如下所示:

redTheme.swift

    func makeRedButton() {    
        self.layer.backgroundColor = myCustomRedcolor  
    }
Run Code Online (Sandbox Code Playgroud)

Aao*_*oIi 7

您可以使用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
            }

        }
Run Code Online (Sandbox Code Playgroud)


bud*_*ino 5

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)
})
Run Code Online (Sandbox Code Playgroud)