Link 方法在 UITextView 的属性文本中的最后一个字符之后被调用

Link methods get called after the last character in attributed text for UITextView

我有一个 textView,它有一个 UITapGesture,它有这个方法作为选择器 - (void)textTapped:(UITapGestureRecognizer *)recognizer。当我在文本视图的最后一行下方或显示的最后一个字符之后点击一点时,它将调用我最后一个字符的属性文本上的方法,因为它看起来是:layoutManager characterIndexForPoint:location inTextContainer:textView.textContainer fractionOfDistanceBetweenInsertionPoints:NULL]; returns 最后一个字符。在这种情况下,我不希望它使用最后一个字符,因为我不希望它进入我的条件语句。我尝试更新逻辑,使其成为 characterIndex < textView.textStorage.length - 1 并且可以很好地处理这种情况,但是如果我点击最后一个字符,则它不会调用该函数。有没有一种方法可以防止最后一个字符在未被点击时被返回,而只是获取被点击的确切字符或其他一些方法来防止调用该方法。

- (void)textTapped:(UITapGestureRecognizer *)recognizer
{
    UITextView *textView = (UITextView *)recognizer.view;

    // Location of the tap in text-container coordinates

    NSLayoutManager *layoutManager = textView.layoutManager;
    CGPoint location = [recognizer locationInView:textView];
    location.x -= textView.textContainerInset.left;
    location.y -= textView.textContainerInset.top;

    // Find the character that's been tapped on

    NSUInteger characterIndex;
    characterIndex = [layoutManager characterIndexForPoint:location
                                           inTextContainer:textView.textContainer
                  fractionOfDistanceBetweenInsertionPoints:NULL];

    if (characterIndex < textView.textStorage.length) {

        NSRange range;
        id value = [textView.attributedText attribute:@"myCustomTag" atIndex:characterIndex effectiveRange:&range];

        // Handle as required...

        NSLog(@"%@, %d, %d", value, range.location, range.length);

    }
}

我认为您需要使用 glyphIndexForPoint 文档而不是使用 characterIndexForPoint,您可以在此处找到相关文档。 Apple Documentation

现在在文档中它清楚地告诉您找到字形后要遵循的步骤,我将引用文档中的段落:

If no glyph is under point, the nearest glyph is returned, where nearest is defined according to the requirements of selection by mouse. Clients who wish to determine whether the the point actually lies within the bounds of the glyph returned should follow this with a call to boundingRectForGlyphRange:inTextContainer: and test whether the point falls in the rectangle returned by that method. If partialFraction is non-NULL, it returns by reference the fraction of the distance between the location of the glyph returned and the location of the next glyph.