【问题标题】:Get word from long tap in a word of UITextView在 UITextView 的一个单词中长按获取单词
【发布时间】:2012-07-05 17:29:06
【问题描述】:

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

【问题讨论】:

标签: objective-c ios uigesturerecognizer uipopovercontroller


【解决方案1】:

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

【讨论】:

  • 您可能想查看文本视图的tokenizer 属性的rangeEnclosingPosition:withGranularity:inDirection: 方法。
  • 谢谢 rob,这让事情变得简单多了!我已经编辑了答案以包含您的建议。
  • 有没有办法像获取单词的位置一样向后执行此操作?
  • @TheDeveloper UITextInput 协议提供了一个函数,如果我想知道 UITextView 的特定偏移量(即字符串中的字符位置)的 UITextPosition:positionFromPosition:(UITextPosition *)startPosition offset:(NSInteger)offset。 startPosition 可以是tv.beginningOfDocument(如果您的Textview 被命名为'tv')并且偏移量是字符串中单词的位置,作为文本分配给textview。要在返回位置获取布局点,请使用来自caretRectForPosition: 的矩形原点
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多