简体   繁体   English

从UITextView的单词中获取单词

[英]Get word from long tap in a word of UITextView

Now I already detect long tap in UITextView 现在我已经在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? 现在,我该如何获取长按的单词内容,并获得该单词的矩形以准备显示PopOver?

This function will return the word at a given position in an UITextView. 此函数将返回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];
}

SWIFT 4 SWIFT 4

A copy of @cayeric's answer written in swift for your convenience. @ 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM