从UITextView的单词中获取单词

时间:2012-07-05 17:29:06

标签: objective-c ios uigesturerecognizer uipopovercontroller

现在我已经在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);
    }

现在,我该怎样做才能获得长按的单词内容,并获得该单词的矩形以准备显示PopOver?

2 个答案:

答案 0 :(得分:15)

此函数将返回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];
}

答案 1 :(得分:0)

SWIFT 4

@ cayeric的答案副本用swift写的,以方便您使用。

func getWord(at position: CGPoint, in textView: UITextView) -> String?{
    var point = position

    //eliminate scroll offset
    point.y += textView.contentOffset.y

    //get location in text from textposition at point
    guard let tapPos = textView.closestPosition(to: point) else {
        return nil
    }

    //fetch the word at this position (or nil, if not available)
    guard let wordRange = textView.tokenizer.rangeEnclosingPosition(tapPos, with: .word, inDirection: UITextWritingDirection.rightToLeft.rawValue) else {
        return nil
    }

    return textView.text(in: wordRange)
}