Get word from long tap in a word of UITextView

拈花ヽ惹草 提交于 2019-12-30 01:29:46

问题


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?


回答1:


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



回答2:


SWIFT 4

A copy of @cayeric's answer written in swift for your convenience.

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)
}


来源:https://stackoverflow.com/questions/11349459/get-word-from-long-tap-in-a-word-of-uitextview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!