Swift 4.1 UILabel Extension:
Add this extension to your code:
extension UILabel {
/** Animates the background color of a UILabel to a new color. */
func animateBackgroundColor(to color : UIColor?, withDuration : TimeInterval, completion : ((Bool) -> Void)? = nil) {
guard let newColor = color else { return }
self.backgroundColor = .clear
UIView.animate(withDuration: withDuration, animations: {
self.layer.backgroundColor = newColor.cgColor
}, completion: completion)
}
}
You should use it like this:
myUILabel.animateBackgroundColor(to: .red, withDuration: 0.5)
Now, if you want to restore the original color, use it like this:
// Storing the orignal color:
let originalColor = myUILabel.backgroundColor
// Changing the background color:
myUILabel.animateBackgroundColor(to: .red, withDuration: 0.5)
// ... Later:
// Restoring the original color:
myUILabel.animateBackgroundColor(to: originalColor, withDuration: 0.5, completion: {
(value: Bool) in
myUILabel.backgroundColor = originalColor
})