NSTextAttachment和触摸事件

时间:2014-03-18 16:34:22

标签: ios7 uitextview textkit

我有一个UITextView(在编辑模式下),只有很少的图像(作为NSTextAttachment)。我想拦截这些触摸事件。

我在UITextView上设置了委托,但永远不会调用textView:shouldInteractWithTextAttachment:inRange:

(从论坛看来,UITextView的editable属性应该是NO才能生效,但不能按照官方文档进行操作。

编辑器看起来像这样: Editor

1 个答案:

答案 0 :(得分:5)

正如您所提到的,textView:shouldInteractWithTextAttachment:inRange:并不适用于可编辑的文本视图。解决这个问题的方法是实现自己的UITapGestureRecognizer并执行以下操作:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    if (self.state == UIGestureRecognizerStateFailed) return;

    UITouch *touch = [touches anyObject];
    UITextView *textView = (UITextView*) self.view;
    NSTextContainer *textContainer = textView.textContainer;
    NSLayoutManager *layoutManager = textView.layoutManager;

    CGPoint point = [touch locationInView:textView];
    point.x -= textView.textContainerInset.left;
    point.y -= textView.textContainerInset.top;

    NSUInteger characterIndex = [layoutManager characterIndexForPoint:point inTextContainer:textContainer fractionOfDistanceBetweenInsertionPoints:nil];

    if (characterIndex >= textView.text.length)
    {
        self.state = UIGestureRecognizerStateFailed;
        return;
    }

    _textAttachment = [textView.attributedText attribute:NSAttachmentAttributeName atIndex:characterIndex effectiveRange:&_range];
    if (_textAttachment)
    {
        return;
    }
    _textAttachment = nil;
}

然后,您将此手势识别器添加到文本视图中,当识别出手势时,您要求_textAttachment值。

请记住characterIndexForPoint:inTextContainer: fractionOfDistanceBetweenInsertionPoints:返回最近的字符索引。您可能想要检查该点是否在附件中,具体取决于您计划执行的操作。