Search code examples
iosswift3core-animation

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


I would like to animate the backgroundColor property of my UIButtons but I'm not sure where to begin. I've never used Core Animation, I'm not sure if I even need it for something so basic?

I've styled the buttons using a class and a method that looks something like this:

redTheme.swift

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

Solution

  • You can do it with UIView Animation as the following :

    Note: Simply don't forget to set the background to clear before you perform the animation otherwise it won't work. That's because animation need a starting and ending point, starting point is clear color to Red. Or alpha 0 to alpha 1 or the other way around.

    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
                }
    
            }