3

I'm trying to change the color of a button's background using the cross dissolve animation, however, whenever I run this it instantly change the color instead of having a smooth transition.

UIView.transition(with: self.SignIn,
                  duration:3,
                  options: UIViewAnimationOptions.transitionCrossDissolve,
                  animations: { self.SignIn.backgroundColor? = UIColor(hexaString: "#" + hex) },
                  completion: nil)
Nirav D
  • 71,513
  • 12
  • 161
  • 183
Max Kortge
  • 527
  • 7
  • 23

2 Answers2

6

Instead of setting backgroundColor in animations block I have set it before the view transition and then start the transition of view and it will work perfectly.

self.btnAnimate.backgroundColor = UIColor.red
UIView.transition(with: self.btnAnimate,
                  duration: 3,
                  options: .transitionCrossDissolve,
                  animations: nil,
                  completion: nil)

Output

enter image description here

Note: I have set red color as backgroundColor you can set what ever color you want.

Nirav D
  • 71,513
  • 12
  • 161
  • 183
-1

This is happening because your animations are conflicting with the default button animations.

To solve this, you can create a custom child class of UIButton:

import UIKit

class CustomButton: UIButton {

    func animateButton(hex: String) {

        // This block disables the default animations
        UIButton.performWithoutAnimation {

            // This is where you define your custom animation
            UIView.transition(with: self, duration:3, options: UIViewAnimationOptions.transitionCrossDissolve, animations: {
                self.backgroundColor? = UIColor(hexaString: "#" + hex) }, completion: nil)

            // You must call layoutIfNeeded() at the end of the block to prevent layout problems
            self.layoutIfNeeded()
        }
    }

}

Then to call this function:

signInButton.animateButton("ffffff") // Pass in your hex string

Of course, be sure to change the class of your loginButton on the story board from UIButton to CustomButton.

The downside to this approach is that the text is still darkened during the animation process. There may be a way to override this (I wasn't able to quickly determine how), so an alternative approach to this solution is to use a UILabel instead of a UIButton and set an on click listener.

Or another approach you might want to consider, is put a customLabel behind a UIButton and perform animations on the label when the button is clicked. Although this approach seems somewhat "hacky", the advantage is that the button is not disabled while the label is being animated, meaning you can register rapid sequential button presses (although it looks like the purpose of your button is to log the user in, in which case this probably wouldn't be necessary for you).

Joshua Wolff
  • 2,687
  • 1
  • 25
  • 42
Austin Wood
  • 368
  • 1
  • 4
  • 14