How can I detect taps on a particular part (substring) of a UILabel?

user2758267 picture user2758267 · Sep 8, 2013 · Viewed 7.8k times · Source

I am new to iOS development. I dont know whether this questions has been asked already or not, I tried searching for the solution on stackoverflow but didn't get any results.

Question :

I have a UILabel called myLabel with the text: "Click here to proceed"

Now the problem is I want to perform an action when user taps only "Click".

I know how to use UITapGestureRecognizer, but it responds to the whole UILabel. Is it possible to just detect when user taps only on string "Click"?

Answer

Jsdodgers picture Jsdodgers · Sep 8, 2013

You could check the location of the touch to see if it is on the word "Click". This may not be completely accurate though and may break if you change the text in your label.

What you could do is first get the location of the click by using:

CGPoint location = [gesture locationInView:gesture.view];

This gets the location of the gesture in your view.

Once you have this, you can either have the size of the word "Click" hard-coded or you can create an identical label to your gesture label to get the size, such as:

UILabel *sizeLabel = //create label with same font.
[sizeLabel setText:@"Click"];
float width = [sizeLabel sizeThatFits:CGSizeMake(MAXFLOAT,MAXFLOAT)].width;

You could also do this when creating the actual label and store this width in a static variable so that you only have to do it once and you don't have to create an extra label (ie set the text of your real label to @"Click", get the width, and then set it to the real text).

Once you have the width, you and the location of the tap, you can check if the word "Click" was tapped by comparing:

if (location.x < width) {
    //Put your tap code in here.
}