Add tap gesture recogniser on a specific word in a UITextView
Asked Answered
S

1

1

I have a UITextView with some text. This text is an Attributed String(NSAttributedString). There are certain portions of the text that i have set to bold, and want to add a TapGestureRecogniser to those specific words only.

Till now, i have been using the textViewDidChangeSelection method of the UITextView delegate. But this is causing issues in other parts of the project.

Is there a more direct approach to this ?

Stradivarius answered 10/7, 2013 at 11:14 Comment(1)
May be u could refer this #15035152Brackett
N
2

You can only add a GestureRecognizer to a view, not to some words. It's a quite complex task, there's no easy solution for it.

I can think in some approaches, for example:

  • Place a transparent view on top of the bold words to get the Tap.
  • Detect the Tap in all the UITextView, and then calculate based on the position of the touch and the position of the bold words if it hit one.

Both options requiere a lot of code and a lot of edge cases where it can fail.

As I said, it's a really complex situation, you may want to keep using textViewDidChangeSelection and fix the issues, we can help you.

Noheminoil answered 10/7, 2013 at 11:20 Comment(4)
Adding transparent views on top of the words would be fine if the text were static. But it is not. It is user editable, and can be appended, by other views.Stradivarius
So the second option then, you need to calculate using the font the size of the string to try to figure out the position, using sizeWithFont:Noheminoil
I have a UITextView, that takes inputs from the user, and also tableviews(cells). The chosen cell's content is appended to the string (or replaces the previous choice), in the textview. The string is then turned into an NSAttributedString. What i want to achieve is that, when the user taps the words (chosen from tables), the tableviews should re-apper, so the user may change their choice(s). Something similar to the STATUS UPDATE view of the Facebook iOS app. If one taps on the tagged friends, or the location, in the textview, the according views reapper. Phew !Stradivarius
Late comment, but your tip worked perfectly for me. Used UITextPosition + UITextGranularity + firstRectForRange.Stradivarius

© 2022 - 2024 — McMap. All rights reserved.