UITextView应检测链接,否则应传播触摸以查看下面的链接

问题描述 投票:3回答:2

我有一个文本视图,我想检测链接,但是当触摸点没有链接时,它应该传播触摸到下面的视图(它当前没有)。它将包含在表格视图单元格中,如果用户点击链接,它应该交互(它可以工作),但是当点击另一个点时,它应该选择表格视图单元格。

我需要文本无法选择,所以我遵循了https://stackoverflow.com/a/27264999/811405并实施:

-(BOOL)canBecomeFirstResponder{
    return NO;
}

它也没有在此之前发送下面的触摸事件,但我已经包括它只是它干扰解决方案的情况。

ios uiview touch
2个回答
8
投票

您需要子类化hitTest方法,以便在链接内部发生单击时返回textView,否则返回nil,而不是阻止文本视图成为第一响应者。

@interface LinkOnlyTextView : UITextView
@end

@implementation LinkOnlyTextView

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    NSUInteger glyphIndex = [self.layoutManager glyphIndexForPoint:point inTextContainer:self.textContainer fractionOfDistanceThroughGlyph:nullptr];
    NSUInteger characterIndex = [self.layoutManager characterIndexForGlyphAtIndex:glyphIndex];
    if (characterIndex < self.textStorage.length) {
        if ([self.textStorage attribute:NSLinkAttributeName atIndex:characterIndex effectiveRange:nullptr]) {
            return self;
        }
    }
    return nil;
}

@end

2
投票

这是@ Dalzhim的答案的Swift版本,结合@jupham的调整来检查point实际上是否包含在glyphRect中。

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

    let glyphIndex = self.layoutManager.glyphIndex(for: point, in: self.textContainer)

    //Ensure the glyphIndex actually matches the point and isn't just the closest glyph to the point
    let glyphRect = self.layoutManager.boundingRect(forGlyphRange: NSRange(location: glyphIndex, length: 1), in: self.textContainer)

    if glyphIndex < self.textStorage.length,
        glyphRect.contains(point),
        self.textStorage.attribute(NSAttributedStringKey.link, at: glyphIndex, effectiveRange: nil) != nil {

        return self
    } else {
        return nil
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.