Transition of a UIButton Image from One Image to Another

I am new to iOS development and use Swift as my language of choice. I am developing a simple little program for my son that displays animal images on UIButtons, and when he selects the correct one, all buttons load new images, and he asked to find another animal.

The basics of the program are up and running, and he can play it, but now I want to make it more attractive. When the correct image is selected, and it's time to replace the button images with new ones, I use:

btnItem.setImage(UIImage(named: arrItems[intItemCounter]), forState: .Normal) 

Instead of just changing the button image from one to another, I want to do this with an animated transition, but I cannot figure out how to do it.

I found a lot in common with transitions to UIViews and a lot to do with constantly animated button images, but nothing for transitions like dissolving or scrolling from left to right or something else.

This SO question is almost the same as mine, but the answer uses Objective-C.

So, a long story, is there a way to transition a UIButton image from one to another in Swift?

Thanks for your time in advance.

+6
source share
1 answer

Update below with Swift 4.0

  UIView.transition(with: sender as! UIView, duration: 1.5, options: .transitionFlipFromRight, animations: { sender.setImage(UIImage(named: arrItems[intItemCounter]), for: .normal) }, completion: nil) 

UIButton is a subclass of UIView, so you can use UIView.animateWithDuration with a button. For example, you might say something like:

 @IBAction func buttonPressed(sender: UIButton) { UIView.transitionWithView(sender, duration: 1.5, options: .TransitionFlipFromRight, animations: { sender.setImage(UIImage(named: arrItems[intItemCounter]), forState: .Normal) }, completion: nil) } 

This will cause the button to switch with the new image.

If you need animation from another example (fade / in), you can say:

 @IBAction func buttonPressed(sender: UIButton) { UIView.animateWithDuration(0.5, animations: { sender.alpha = 0.0 }, completion:{(finished) in sender.setImage(UIImage(named: arrItems[intItemCounter]), forState: .Normal) UIView.animateWithDuration(0.5,animations:{ sender.alpha = 1.0 },completion:nil) }) } 

You can also make the cross so that:

 @IBAction func buttonPressed(sender: UIButton) { UIView.transitionWithView(sender, duration: 1.5, options: .TransitionCrossDissolve, animations: { sender.setImage(UIImage(named: arrItems[intItemCounter]), forState: .Normal) }, completion: nil) } 
+17
source

All Articles