How to animate the background color of a UILabel?
I can't find it documented anywhere, but it appears the backgroundColor
property of UILabel
is not animatable, as your code works fine with a vanilla UIView
. This hack appears to work, however, as long as you don't set the background color of the label view itself:
#import <QuartzCore/QuartzCore.h>...theLabel.layer.backgroundColor = [UIColor whiteColor].CGColor;[UIView animateWithDuration:2.0 animations:^{ theLabel.layer.backgroundColor = [UIColor greenColor].CGColor;} completion:NULL];
Swift
(important) Set the UILabel's background color to clear (either in IB or in code). For example:
override func viewDidLoad() { super.viewDidLoad() myLabel.backgroundColor = UIColor.clear}
Animate the layer background color.
@IBAction func animateButtonTapped(sender: UIButton) { UIView.animate(withDuration: 1.0, animations: { self.myLabel.layer.backgroundColor = UIColor.red.cgColor })}
Note that CGColor
is added after the UIColor
.
Result
Swift 3
To animate your label background color from white to green, set up your label like this:
self.labelCorrection.backgroundColor = UIColor.clearself.labelCorrection.layer.backgroundColor = UIColor.white.cgColor
Animate like this:
UIView.animate(withDuration: 2.0) { self.labelCorrection.layer.backgroundColor = UIColor.green.cgColor}
To go back to the original state, so you can animate again, make sure you remove animations:
self.labelCorrection.layer.backgroundColor = UIColor.white.cgColorself.labelCorrection.layer.removeAllAnimations()