UIView ClickListener : Swift

Suneet Agrawal
2 min readDec 14, 2020

--

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:)))
self.myView.addGestureRecognizer(gesture)

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.

--

--