Reputation: 35
I am trying to animate UILabel textColor changes using UIView.animate. However, nothing is changing when I attempt to use UIView. Here is my code:
titleLabel.textColor = UIColor(red: 104/250, green: 155/250, blue: 121/250, alpha: 1)
UIView.animate(withDuration: 1.0, animations: {
self.titleLabel.textColor = UIColor(red:206/255, green: 206/255, blue: 206/255, alpha: 1.0)
I expect the color of the label to change to a greenish color and then change back to the gray-ish color it was before. Thanks in advance for helping!
Upvotes: 2
Views: 178
Reputation: 1318
The textColor
property is not specified as being animatable in Apple developer docs, so I don't think you can do it with a simple UIView animations
block.
You can use UIView transition
instead.
Code:
UIView.transition(with: self.titleLabel, duration: 1.0, options: .transitionCrossDissolve, animations: {
self.titleLabel.textColor = UIColor(red: 104/250, green: 155/250, blue: 121/250, alpha: 1)
}, completion: { _ in
self.titleLabel.textColor = UIColor(red:206/255, green: 206/255, blue: 206/255, alpha: 1.0)
})
I hope it will help you. Let me know if you are still having any issue.
Upvotes: 1
Reputation: 2805
TextColor is not supposed to be animatable in the documentation so you have to perform below animation code.
Reason:
The reason that textColor is not animatable is that UILabel uses a regular CALayer instead of a CATextLayer. so you have two options
let changeColor = CATransition() changeColor.duration = 1 CATransaction.begin() CATransaction.setCompletionBlock { self.titleLabel.layer.add(changeColor, forKey: nil) self.titleLabel.textColor = UIColor(red:206/255, green: 206/255, blue: 206/255, alpha: 1.0) } titleLabel.textColor = UIColor(red: 104.0/255.0, green: 155.0/255.0, blue: 121.0/255.0, alpha: 1.0) CATransaction.commit()
Upvotes: 0
Reputation: 43
try
UIView.animate(withDuration: 1.0, animations: {
self.titleLabel.textColor = UIColor(red:206/255, green: 206/255, blue: 206/255, alpha: 1.0)
self.view.layoutIfNeeded()
}
Upvotes: 0