Christian Giacomi

UILabel tap gesture in Swift

Posted — Feb 18, 2019

In iOS there are situations where a UIButton will not be exactly what you need. One of these, at least in my case has been when creating my UI via the Storyboard. I have found that embedding a UILabel in a UITableViewCell is a much simpler process that attempting to so so with a UIButton.

Therefore I have found myself using a UILabel more than once instead of a UIButton. Unfortunately a label does not respond exactly like a button, specifically when you tap the label, nothing happens by default.

To mimic the behavior of a UIButton you need to do a few simple things.

// Define your label as an implicitly unwrapped optional
@IBOutlet var label: UILabel!

// Set the label to accept user interactions
label.isUserInteractionEnabled = true

// Define your gesture and set a target and selector
let tapGesture = UITapGestureRecognizer(
    target: self,
    action: #selector(onLabelTap(tapGestureRecognizer:))

// Bind it to the label

And of course you will need a selector to be invoked when the tap gesture is recognized.

@objc func onLabelTap(tapGestureRecognizer: UITapGestureRecognizer) {
    // Add your custom code here

This will allow you to mimic the same user experience as if you had used a UIButton

If you are using Swift 4.0 you will also need to use @objc in the signature of the method. That is all, and now your UILabel will respond to user taps just like a UIButton would.

If this post was helpful tweet it or share it.