I'm new to iOS development and am using Swift as my language of choice. I'm developing a simple little program for my son which displays images of animals on UIButtons and when he picks the right one all the buttons load new images and he's asked to find a different animal.
The basics of the program are up and running and he can play it but now I want to get on to making it fancier. 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)
Rather than simply changing a button's image from one to another I want to do the change with an animated transition but I can't figure out how.
I've found plenty to do with transitions on UIViews and plenty to do with permanently animating button images but nothing for transitions such as a dissolve or a swipe from left to right or whatever.
This question on SO is pretty much the same as mine but the answer uses Objective-C.
So, long story short, is there a way of transitioning a UIButton image from one to another in Swift?
Thanks for your time in advance.
Updating 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 can 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) }
Which will cause, on tapping, the button to flip with the new image.
If you want the animation from the other example (fade out/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 do a cross dissolve like so:
@IBAction func buttonPressed(sender: UIButton) { UIView.transitionWithView(sender, duration: 1.5, options: .TransitionCrossDissolve, animations: { sender.setImage(UIImage(named: arrItems[intItemCounter]), forState: .Normal) }, completion: nil) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With