UIView ClickListener : Swift

Adding a click event to a UIView is something which is required most of the times. For views like UIButton, we can simply connect an IBAction with the event type and detect the click events but sometimes we need it for Lable or even other views.

If you try to add an IBAction to your view, you won’t get Action as an option while connecting it with ViewController.

This post was originally posted at https://agrawalsuneet.github.io/blogs/uiview-clicklistener-swift/ and reposted on Medium on 14th Dec 2020.

The only possible way to add a click event on UIView is using UITapGestureRecognizer. You can either add an UITapGestureRecognizer using interface builder or you can do it programmatically.

//swift code in view controller

let gesture = UITapGestureRecognizer(target: self, action: #selector(self.clickAction(sender:)))

func clickAction(sender : UITapGestureRecognizer) {
// Do what you want

This way is a bit inefficient as we need to add one function for each view which will be clickable.

There is a better way where we can add this functionality to each view without making our class messy.
We can add this to the UIView extension itself which will be a very clean approach and will make our life super easy.

First, extend UITapGestureRecognizer and add a property to it which holds a function which takes 0 params and is of Void return type.

class ClickListener: UITapGestureRecognizer {
var onClick : (() -> Void)? = nil

Now create an extension to UIView class and add a method which takes an escaping type of variable which is the reference to a function which need to be run if the view clicked.

Please continue reading at https://agrawalsuneet.github.io/blogs/uiview-clicklistener-swift/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store