5

现在我已经在 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?

4

2 回答 2

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];
}
于 2012-07-11T21:29:15.230 回答
0

斯威夫特 4

为方便起见,用 swift 编写的@cayeric 答案的副本。

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)
}
于 2018-05-18T00:45:50.597 回答