How to get UILabel to respond to tap?

I have discovered that I can create UILabel much faster than UITextField and I plan to use UILabel most of the time for my data display app.

To make a long story short though, I wish to let the user tap on a UILabel and have my callback respond to that. Is that possible?

Thanks.


You can add a UITapGestureRecognizer instance to your UILabel.

For example:

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTapped)];
tapGestureRecognizer.numberOfTapsRequired = 1;
[myLabel addGestureRecognizer:tapGestureRecognizer];
myLabel.userInteractionEnabled = YES;

If you're using storyboards you can do this entire process in the storyboard with no additional code. Add a label to the storyboard, then add a tap gesture to the label. In the Utilities pane, make sure "User Interaction Enabled" is checked for the label. From the tap gesture (at the bottom of your view controller in the storyboard), ctrl+click and drag to your ViewController.h file and create an Action. Then implement the action in the ViewController.m file.


Swift 3.0

Initialize the gesture for tempLabel

tempLabel?.text = "Label"
let tapAction = UITapGestureRecognizer(target: self, action: #selector(self.actionTapped(_:)))
tempLabel?.isUserInteractionEnabled = true
tempLabel?.addGestureRecognizer(tapAction)

Action receiver

func actionTapped(_ sender: UITapGestureRecognizer) {
    // code here
}

Swift 4.0

Initialize the gesture for tempLabel

tempLabel?.text = "Label"
let tapAction = UITapGestureRecognizer(target: self, action:@selector(actionTapped(_:)))
tempLabel?.isUserInteractionEnabled = true
tempLabel?.addGestureRecognizer(tapAction)

Action receiver

func actionTapped(_ sender: UITapGestureRecognizer) {
    // code here
}