UILabel tap gesture in Swift

How to use a UILabel like a UIButton in Swift

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// 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
label.addGestureRecognizer(tapGesture)

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

1
2
3
@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.

Built with Hugo
Theme Stack designed by Jimmy