How to customize UILabel clickable

The most simple way is to just add a gesture recognizer to the actual view (be it a UILabel or some custom view of your own). In order for the gesture recognizer to work, the view must be set userInteractionEnabled.

Here’s an example, assuming that your label view (or whatever it is) is called labelView:

UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userTappedOnLink:)];
// if labelView is not set userInteractionEnabled, you must do so
[labelView setUserInteractionEnabled:YES];
[labelView addGestureRecognizer:gesture];

In this example, an action message will be sent to self and the message would be defined as

- (void)userTappedOnLink:(UIGestureRecognizer*)gestureRecognizer;

This works the same as wiring up any other UIControl subclass, such as a button.

Other notes: don’t try to add the same gesture recognizer to multiple views, it won’t work. Don’t add more than one copy of the gesture recognizer to multiple views (it doesn’t replace them, it just stacks them up and wastes memory). You should add the gesture recognizer when you initially create and configure your view.

For more information, see the documentation for UIGestureRecognizer.

Leave a Comment