Nathan C
Nathan C

Reputation: 286

How can I animate the background color of a label using Swift

I have this code the animate the background color perfectly:

UIView.animate(withDuration: 2, delay: 0.0, options:[UIViewAnimationOptions.repeat, UIViewAnimationOptions.autoreverse], animations: {
        self.view.backgroundColor = UIColor(red: 0/255, green: 185/255, blue: 215/255, alpha: 1.0)
        self.view.backgroundColor = UIColor(red: 0/255, green: 78/255, blue: 215/255, alpha: 1.0)
        self.view.backgroundColor = UIColor(red: 0/255, green: 215/255, blue: 138/255, alpha: 1.0)
}, completion: nil)

But then I tried to use it to animate the background color of a label, but in a darker color, and it didn't work:

UIView.animate(withDuration: 2, delay: 0.0, options:[UIViewAnimationOptions.repeat, UIViewAnimationOptions.autoreverse], animations: {
        self.topBar.backgroundColor = UIColor(red: 0/255, green: 159/255, blue: 184/255, alpha: 1.0)
        self.topBar.backgroundColor = UIColor(red: 0/255, green: 67/255, blue: 184/255, alpha: 1.0)
        self.topBar.backgroundColor = UIColor(red: 0/255, green: 184/255, blue: 117/255, alpha: 1.0)
}, completion: nil)

Is there something wrong, or what can I do to animate the background color of a label?

Upvotes: 0

Views: 1882

Answers (1)

0x384c0
0x384c0

Reputation: 2294

try animate layer.backgroundColor instead backgroundColor

this code works for me

    UIView.animate(withDuration: 2, delay: 0.0, options:[UIViewAnimationOptions.repeat, UIViewAnimationOptions.autoreverse], animations: {
        self.label.layer.backgroundColor = UIColor(red: 0/255, green: 185/255, blue: 215/255, alpha: 1.0).cgColor
        self.label.layer.backgroundColor = UIColor(red: 0/255, green: 78/255, blue: 215/255, alpha: 1.0).cgColor
        self.label.layer.backgroundColor = UIColor(red: 0/255, green: 215/255, blue: 138/255, alpha: 1.0).cgColor
    }, completion: nil)

Upvotes: 3

Related Questions