Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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  
    }
like image 200
Brewski Avatar asked Dec 15 '16 11:12

Brewski


1 Answers

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
            }

        }
like image 195
AaoIi Avatar answered Oct 19 '22 14:10

AaoIi