Add a tap gesture to a part of a UILabel -iOS Swift

Bruno Chen Chih Ying
1 min readJan 18, 2021

--

Imagine you can easily add a method when clicking on a part of the text label, like this:

For that we need 2 steps.

Step 1: Implement UILabel extension

To get started, we need implement UILabel extension.

1- We need create a typealias for the method type.

2- Create addRangeGesture method with stringRange and function parameters. This method is responsible for adding gesture recognizer for entire UILabel. Let’s save the parameters in the RangeGestureRecognizer class (Step 2).

3- Create objc method tappedOnLabel, this will use didTapAttributedTextInLabel (step 2) to check if the string is in range, if is in range he running the method.

Step 2: Create RangeGestureRecognizer class

We will create a class for gesture to be able to store the variables, because the extension does not allow to store data.

This class is responsible for checking if the string is in range and return boolean.

Using:

--

--