Skip to main content

UIView UITapGestureRecognizer

Adding a UITapGestureRecognizer to a UIView is very straighforward. All you do is setup the gesture and then assign it to the view. Could not be much easier could it.

There are a couple of points just to hightlight.

Firstly if you are using a UIImageView then you will need to add in the following extra line before you add the gesture.

Secondly I just want to mention the Selector part. This has changed in Swift from being

to what you see in the example where you reference the selection method with the class of the UIViewController

Recently I have started putting these selector references into Selector extensions. Here I set an extension on the Selector class itself and then use a static variable to set the selector.

Back in my UITapGestureRecognizer, I can now just reference that static variable and even use dot notation as Xcode will know its a Selector instance.

How you implement the Selector call will come down to your preference and it may be that a best practice will evolve with these items, but setting gestures on your views and making your application more interactive is certainly very easy.

Please follow and like us: