Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get word from long tap in a word of UITextView

Now I already detect long tap in UITextView

    - (void)viewDidLoad
    {
         [super viewDidLoad];
         UILongPressGestureRecognizer *LongPressgesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressFrom:)];    
         [[self textview] addGestureRecognizer:LongPressgesture];
         longPressGestureRecognizer.delegate = self;
    }
    - (void) handleLongPressFrom: (UISwipeGestureRecognizer *)recognizer
    {
         CGPoint location = [recognizer locationInView:self.view];

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

Now, How should I do to get content of word which got long press, and get a rect of that word to prepare to show the PopOver?

like image 325
Huy Tran Avatar asked Jul 05 '12 17:07

Huy Tran


1 Answers

This function will return the word at a given position in an UITextView.

+(NSString*)getWordAtPosition:(CGPoint)pos inTextView:(UITextView*)_tv
{
    //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];

    return [_tv textInRange:wr];
}
like image 123
cayeric Avatar answered Oct 20 '22 00:10

cayeric