How to detect tapped word in UItextview

Posted by Sachin Joshi
3
Dec 15, 2015
157 Views
download

We might face a situation when we need to add action on tapping a particular word from a string on the iPhone screen like a link or a hashtag etc. Now though we can easily add a UITapGestureRecognizer on a UITextView or UILabel, finding the exact tapped word is tricky. Here is how to do this (using UITextView and UILongPressGestureRecognizer) : i) Add gesture recognizer to text view

i) Add gesture recognizer to text view

  1. UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressResponse:)];
  2.     [textViewDescription addGestureRecognizer:longPress];

   ii) Handle gesture recognizer

  1. - (void)longPressResponse:(UILongPressGestureRecognizer *)recognizer {
  2.     if (recognizer.state == UIGestureRecognizerStateBegan) {
  3.         CGPoint location = [recognizer locationInView:textViewDescription];
  4.         NSString *tappedWord = [self wordAtPosition:CGPointMake(location.x, location.y)];
  5.         NSLog(@"tappedWord %@",tappedWord);
  6.     }
  7. }

iii) Get tapped word

  1. - (NSString *)wordAtPosition:(CGPoint)position
  2. {
  3.     //eliminate scroll offset
  4.     position.y += textViewDescription.contentOffset.y;
  5.     //get location in text from textposition at point
  6.     UITextPosition *tapPosition = [textViewDescription closestPositionToPoint:position];
  7.     //fetch the word at this position (or nil, if not available)
  8.     UITextRange *textRange = [textViewDescription.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight];
  9.     
  10.     NSString *tappedWord = [[NSString alloc]initWithString:[textViewDescription textInRange:textRange]];
  11.     
  12.     int start = [textViewDescription offsetFromPosition:textViewDescription.beginningOfDocument toPosition:textRange.start];
  13. ..............
Read full blog at our highly specific C, Java, PHP, Javascript, iPhone, android developer forum about the topic described above How to detect tapped word in UItextview. You can also learn much more about different programming technologies and can enhance your tech skills.
1 people like it
avatar
Comments
avatar
Please sign in to add comment.