Matthew Kim
Matthew Kim

Reputation: 35

UIView.animate not Animating

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

Answers (3)

Amir Khan
Amir Khan

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

Muhammad Waqas Bhati
Muhammad Waqas Bhati

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

  1. perform animation on CATextLayer
  2. Add custom animation layer as given below in the code.
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

hammam abdulaziz
hammam abdulaziz

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

Related Questions