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.





Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

URQL the highly customizable and versatile GraphQL client

Are you spending some time to upskill yourself?

An Introduction to AWS IoT Core

Ansible Playbooks | Loops | Handlers

How the Vmware VExpert Program Improved My Technological Experience

Creating variables and assigning values

CTF — Hacker101 —Micro-CMS v2

What I Learned at Work this Week: SQL Table Partitioning

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
Suneet Agrawal

Suneet Agrawal


More from Medium

Access specifiers in Swift

apple/swift-evolution 上關於 guard 的有趣討論

Async Await in Swift

Hashable in Swift