skip to Main Content

Question

I am trying to animate a UIView color from light grey to dark grey and a UIButton title color from blue to orange.

The animation is meant to take place over 3 seconds when the UIButton is tapped.

The UIView changes color over 3 seconds, but the UIButton does not, and instantly changes color.

  • Why is the UIButton title color animation not working as intended?

  • How do I get the animation to work specifically using UIView.animate?

Thank you.


Code

import UIKit

class ViewController: UIViewController {
    
    let button = UIButton(type: .system)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Set view colour
        self.view.backgroundColor = .lightGray

        // Set initial title color
        button.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
        button.setTitle("Button", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 50)
        view.addSubview(button)
        
        // Add tap gesture recognizer to trigger animation
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(buttonTapped))
        button.addGestureRecognizer(tapGesture)

    }
    
    @objc func buttonTapped() {
        
        // Animate the change of view and title color
        UIView.animate(withDuration: 3, delay: 0, options: [.beginFromCurrentState, .curveEaseInOut], animations: {
            self.view.backgroundColor = .darkGray
            self.button.setTitleColor(.orange, for: .normal)
        })
        
    }
    
}

2

Answers


  1. Please try like this on buttonTapped() function:

    UIView.animate(withDuration: 3, delay: 0, options: [.beginFromCurrentState, .curveEaseInOut], animations: {
            self.view.backgroundColor = .darkGray
        })
        
    UIView.animate(withDuration: 3, delay: 0, options: [.beginFromCurrentState, .curveEaseInOut], animations: {
        self.button.setTitleColor(.orange, for: .normal)
    })
    
    Login or Signup to reply.
  2. Calling setTitleColor(_:for:) method of UIButton does not animate the color change because it’s not animatable. Similar to https://stackoverflow.com/a/67323728/8263578.

    If you are okay without UIView.animate method, you can use this code block:

    // Animate the change of button title color
    UIView.transition(with: button, duration: 3, options: [.transitionCrossDissolve, .beginFromCurrentState], animations: {
        self.button.setTitleColor(.orange, for: .normal)
    }, completion: nil)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search