12

I'm trying to get a word from a tap. The following function's sender is from the UIGesture on the UITextView, sentence.

- (IBAction)printWordSelected:(id)sender {
    NSLog(@"Clicked");

    CGPoint pos = [sender locationInView:self.view];
    UITextView *_tv = sentence;

    NSLog(@"Tap Gesture Coordinates: %.2f %.2f", pos.x, pos.y);

    //eliminate scroll offset
    pos.y += _tv.contentOffset.y;

    //get location in text from textposition at point
    UITextPosition *tapPos = [_tv closestPositionToPoint:pos];

    //fetch the word at this position (or nil, if not available)
    UITextRange * wr = [_tv.tokenizer rangeEnclosingPosition:tapPos withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight];

    NSLog(@"WORD: %@", [_tv textInRange:wr]);
}

This is what I already have, but it prints the word out as NULL

rihekopo
  • 3,241
  • 4
  • 34
  • 63
KBouldin9
  • 404
  • 1
  • 7
  • 19
  • 8
    Try changing pos to **pos = [sender locationInView:_tv]** and then remove the pos.y adjustment. – rmaddy Oct 14 '12 at 17:48
  • Please check http://stackoverflow.com/questions/8811909/getting-the-word-touched-in-a-uilabel-uitextview/21577829#21577829 – TheTiger Feb 05 '14 at 12:53

1 Answers1

10

"Try changing pos to pos = [sender locationInView:_tv] and then remove the pos.y adjustment. – rmaddy"

KBouldin9
  • 404
  • 1
  • 7
  • 19
  • This works well unless the UITextview is not scrolled. But when we scroll the textview, correct word is not printed. – Amrit Sidhu Sep 23 '17 at 05:44