Adding Gesture Recognizers with Closures Instead of Selectors

The worst part about adding a UITapGestureRecognizer or any sort of gesture recognizer/target action is implementing a new function solely for the selector parameter. Today I’d like to share a neat trick I threw together that let’s you add gesture recognizers without selectors.

Let’s say we have a UIImageView in our View Controller and we want to add a UITapGestureRecognizer to it that prints out a statement whenever it’s tapped.

Normally we would create an instance of a UITapGestureRecognizer and set it’s target to the View Controller and its selector as some function we quickly threw together (myImageViewTapped(sender: UITapGestureRecognizer)). This can get a bit redundant and can lead to messy code with functions for every subview you want to add interactivity to.

I got to thinking that I could just make a quick extension that adds tap gesture recognizers to my image view for me, but then I’d have to make a new function for each recognizer, right? Wrong! Using the power of associated objects, we can actually store closures as computed properties in our extension!

Now whenever we want to add a UITapGestureRecognizer to a UIView or UIView subclass like UIImageView, we can do so without creating associated functions for selectors! Here’s an example:

No instances of UITapGestureRecognizers, no targets, no selectors, no unnecessary functions!

Let me know what you think on Twitter :^)