John Leonardo John Leonardo - 1 month ago 26
Swift Question

How do I animate a UIImageView on tap gesture?

So for my app, I have two UIImageViews that have tap gestures. Don't ask why I didn't use buttons; it just made sense at the time for my situation. So here's my problem:

They work, and everything is fine and dandy, but there is zero response out of the box for tap gesture recognizer. Does anybody know an easy library or some simple code that can at LEAST make the UIImageView "pop" on tap, or something like that? I am really just looking for any way to animate these views on tap, so the user feels like they're actually doing something.

Answer

Since animation is basically a change of appearance you could change UIImageView's alpha for a second...

This example functions changes yourImageView.alpha to 0.75 and during 0.5 seconds back to 1.0.

Swift 2:

func handleTap(gestureRecognizer: UIGestureRecognizer) {

       yourImageView.alpha = 0.75
       UIView.animateWithDuration(0.5) {
            yourImageView.alpha = 1.0
       }
}

Swift 3:

func handleTap(gestureRecognizer: UIGestureRecognizer) {

    yourImageView.alpha = 0.75
    UIView.animate(withDuration: 0.5) { 
        yourImageView.alpha = 1.0
    }
}