marcelosalloum
marcelosalloum

Reputation: 3531

How to add different UITapGestureRecognizer to many parts of a single UILabel?

For example, I would like to show a UILabel with links to many user profiles, like:

"[John], [Josef], [Doe], [May] and [You] like this"

The idea is that every [name] calls a different TapGestureRecognizer.

Another option would be create different UILabels and concatenating them like strings but no idea how to do that either.

Upvotes: 1

Views: 236

Answers (2)

jrturton
jrturton

Reputation: 119242

Tappable individual words in displayed text have already been invented for you: use a UIWebView instead of a label. Format your text as HTML, making each name a link, and use the web view delegate methods to see what has been tapped on.

Upvotes: 1

Bill Patterson
Bill Patterson

Reputation: 2558

It's true that you can't attach gesture recognizers to only certain sections of a UIView. And a Label is a single UIView, so using just those two pieces there is no solution other than intercepting the touchesBegan and trying to figure out base don touch coordinates which word it was.

If you want to go that route, you'll find this helpful:

NSString* text = @"John";
CGSize size = [text sizeWithFont:font];

That allows you to figure out the size of drawn text in a given font (the font your label is using) and then do some horrible math to figure out where your words are and compare that the touch locations.

Another possibility is to use separate UILabels for each word. Again, you'd use the sizeWithFont but now you're using it to set the label.frame.size.width for each label to just fit the given text. You can then write code to set the .frame's of all your labels so they line up next to each other.

NSString* text = @"John";
CGSize size = [text sizeWithFont:font];
CGRect frame = myUILabelObject.frame;
frame.size.width = size.width;
myUILabelObject.frame = frame;
// Now next label, setting label.frame to position it next to this label.

Upvotes: 1

Related Questions