我有一个 UITextView(在编辑模式下),里面的图片很少(作为 NSTextAttachment)。我想拦截这些触摸事件。
我在 UITextView 上设置了一个委托,但从textView:shouldInteractWithTextAttachment:inRange:
未被调用。
(从论坛看来,UITextView 的editable
属性应该是NO
为了这个工作,但不是按照官方文档)
编辑器看起来像这样:
我有一个 UITextView(在编辑模式下),里面的图片很少(作为 NSTextAttachment)。我想拦截这些触摸事件。
我在 UITextView 上设置了一个委托,但从textView:shouldInteractWithTextAttachment:inRange:
未被调用。
(从论坛看来,UITextView 的editable
属性应该是NO
为了这个工作,但不是按照官方文档)
编辑器看起来像这样:
正如您所提到的,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:
返回最近的字符索引。您可能需要检查该点是否在附件内,具体取决于您计划执行的操作。