在UITextView中从tap中获取单词

时间:2012-10-14 17:07:43

标签: objective-c ios

我正试图从水龙头中获取一个字。以下函数的sender来自UIGesture上的UITextView句子。

- (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]);
}

这就是我已经拥有的,但它将单词输出为NULL

1 个答案:

答案 0 :(得分:10)

“尝试将pos更改为pos = [sender locationInView:_tv],然后删除pos.y调整。 - rmaddy”