17

NSTextAttachment检测用户何时在 iOS上点击的最佳方法是什么?

我认为其中一种方法是检查 carret 位置上的字符是否是NSAttachmentCharacter,但这似乎不正确。

我也试过UITextViewDelegate方法:-(BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange但它没有被调用textView.editable=YES

4

8 回答 8

7

乔希的回答几乎是完美的。但是,如果您在输入末尾之后点击 UITextView 的空格,glyphIndex(for:in:fractionOfDistanceThroughGlyph)将返回字符串中的最终字形。如果这是您的附件,它将错误地评估为真。

苹果的文档说:如果点下没有字形,则返回最近的字形,其中最近是根据鼠标选择的要求定义的。希望确定该点是否实际上位于返回的字形范围内的客户应在此之后调用 boundingRect(forGlyphRange:in:) 并测试该点是否落在该方法返回的矩形中。

因此,这是一个调整后的版本(Swift 5,XCode 10.2),它对检测到的字形的边界进行了额外的检查。我相信一些characterIndex测试现在是多余的,但它们不会伤害任何东西。

一个警告:字形似乎延伸到包含它们的行的高度。如果您在横向图像附件旁边有一个高纵向图像附件,则点击横向图像上方的空白仍将评估为 true。

import UIKit
import UIKit.UIGestureRecognizerSubclass

// Thanks to https://stackoverflow.com/a/52883387/658604
// and https://stackoverflow.com/a/49153247/658604

/// Recognizes a tap on an attachment, on a UITextView.
/// The UITextView normally only informs its delegate of a tap on an attachment if the text view is not editable, or a long tap is used.
/// If you want an editable text view, where you can short cap an attachment, you have a problem.
/// This gesture recognizer can be added to the text view, and will add requirments in order to recognize before any built-in recognizers.
class AttachmentTapGestureRecognizer: UITapGestureRecognizer {

    typealias TappedAttachment = (attachment: NSTextAttachment, characterIndex: Int)

    private(set) var tappedState: TappedAttachment?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        tappedState = nil

        guard let textView = view as? UITextView else {
            state = .failed
            return
        }

        if let touch = touches.first {
            tappedState = evaluateTouch(touch, on: textView)
        }

        if tappedState != nil {
            // UITapGestureRecognizer can accurately differentiate discrete taps from scrolling
            // Therefore, let the super view evaluate the correct state.
            super.touchesBegan(touches, with: event)

        } else {
            // User didn't initiate a touch (tap or otherwise) on an attachment.
            // Force the gesture to fail.
            state = .failed
        }
    }

    /// Tests to see if the user has tapped on a text attachment in the target text view.
    private func evaluateTouch(_ touch: UITouch, on textView: UITextView) -> TappedAttachment? {
        let point = touch.location(in: textView)
        let glyphIndex: Int = textView.layoutManager.glyphIndex(for: point, in: textView.textContainer, fractionOfDistanceThroughGlyph: nil)
        let glyphRect = textView.layoutManager.boundingRect(forGlyphRange: NSRange(location: glyphIndex, length: 1), in: textView.textContainer)
        guard glyphRect.contains(point) else {
            return nil
        }
        let characterIndex: Int = textView.layoutManager.characterIndexForGlyph(at: glyphIndex)
        guard characterIndex < textView.textStorage.length else {
            return nil
        }
        guard NSTextAttachment.character == (textView.textStorage.string as NSString).character(at: characterIndex) else {
            return nil
        }
        guard let attachment = textView.textStorage.attribute(.attachment, at: characterIndex, effectiveRange: nil) as? NSTextAttachment else {
            return nil
        }
        return (attachment, characterIndex)
    }
}
于 2019-04-25T17:00:41.343 回答
3

委托方法确实有效,但前提是附件在图像属性中有图像并且可编辑 = 否!因此,如果您从其他地方将图像粘贴到属性字符串中,则数据似乎最终存储在 fileWrapper 中,下次您将属性字符串放回 textView 时,图像属性为 nil 并且布局管理器或任何获取图像的东西从文件包装器。

在文档的某处,它确实提到 NSTextAttachment 中没有用于持久化图像属性的方法。

要对此进行测试,请尝试从 Photo 应用程序复制一张照片并将其粘贴到您的 textView 中,现在如果您按住手指,您应该会看到默认菜单弹出。现在如果你保存这个富文本,说成一个核心数据实体,然后检索它,图像属性将为 nil,但图像数据将在attachment.fileWrapper.regularFileContents

这很痛苦,我很想知道工程师的意图。所以你似乎有两个选择。

  1. 创建您自己的自定义 NSTextAttachment 并包含用于存档图像和其他设置的方法(请在您弄清楚这一点时告诉我如何做)
  2. 每次将字符串放回 textView 之前,您都会找到所有附件并重新创建图像属性,如下所示:

    attachment.image = [UIImage imageWithData:attachment.fileWrapper.regularFileContents];

请记住,这样做的副作用是使 fileWrapper 无效。我想调整图像大小,但也要保留原始图像,这样我就不会失去完整的分辨率。我认为这样做的唯一方法可能是继承 NSTextAttachment。

编辑:

我想出了如何创建自定义 NSTextAttachments - 这是一个链接给那些感兴趣的人http://ossh.com.au/design-and-technology/software-development/implementing-rich-text-with-images-on-os -x 和 ios/

编辑 2:要在编辑模式下自定义菜单,请参阅以下 Apple 文档,问题是“touchEnded”似乎从未被调用,因此您可能不得不尝试使用 touchesBegan。小心不要干扰默认的编辑行为。

https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/AddingCustomEditMenuItems/AddingCustomEditMenuItems.html

请注意,在下面的代码中,您需要在// selection management注释后添加代码以确定触摸了哪个字符,检查它是否是特殊文本附件字符,然后修改编辑菜单或采取其他措施。

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *theTouch = [touches anyObject];

    if ([theTouch tapCount] == 2  && [self becomeFirstResponder]) {

        // selection management code goes here...

        // bring up edit menu.
        UIMenuController *theMenu = [UIMenuController sharedMenuController];
        CGRect selectionRect = CGRectMake (currentSelection.x, currentSelection.y, SIDE, SIDE);
        [theMenu setTargetRect:selectionRect inView:self];
        [theMenu setMenuVisible:YES animated:YES];

    }
}

或者,您可以通过添加菜单项然后修改 canPerformAction 方法来添加自定义菜单。

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    LOG(@"canPerformAction: called");

    if (action == @selector(viewImage)) {
       // Check the selected character is the special text attachment character

       return YES;
    }
   return NO;
}

这是一些附加代码,但它有点挑剔。如果检测到附件,第二种方法只是禁用默认编辑菜单。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    FLOG(@"touchesBegan:withEvent: called");

    if (self.selectedRange.location != NSNotFound) {
        FLOG(@" selected location is %d", self.selectedRange.location);

        int ch;

        if (self.selectedRange.location >= self.textStorage.length) {
            // Get the character at the location
            ch = [[[self textStorage] string] characterAtIndex:self.selectedRange.location-1];
        } else {
            // Get the character at the location
            ch = [[[self textStorage] string] characterAtIndex:self.selectedRange.location];
        }

        if (ch == NSAttachmentCharacter) {
            FLOG(@" selected character is %d, a TextAttachment", ch);
        } else {
            FLOG(@" selected character is %d", ch);
        }
    }

}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    FLOG(@"canPerformAction: called");

        FLOG(@" selected location is %d", self.selectedRange.location);
        FLOG(@" TextAttachment character is %d", NSAttachmentCharacter);

        if (self.selectedRange.location != NSNotFound) {

            int ch;

            if (self.selectedRange.location >= self.textStorage.length) {
                // Get the character at the location
                ch = [[[self textStorage] string] characterAtIndex:self.selectedRange.location-1];
            } else {
                // Get the character at the location
                ch = [[[self textStorage] string] characterAtIndex:self.selectedRange.location];
            }

            if (ch == NSAttachmentCharacter) {
                FLOG(@" selected character is %d, a TextAttachment", ch);
                return NO;
            } else {
                FLOG(@" selected character is %d", ch);
            }

            // Check for an attachment
            NSTextAttachment *attachment = [[self textStorage] attribute:NSAttachmentAttributeName atIndex:self.selectedRange.location effectiveRange:NULL];
            if (attachment) {
                FLOG(@" attachment attribute retrieved at location %d", self.selectedRange.location);
                return NO;
            }
            else
                FLOG(@" no attachment at location %d", self.selectedRange.location);
        }
    return [super canPerformAction:action withSender:sender];
}
于 2013-10-25T01:27:08.273 回答
3

苹果让这变得非常困难。正如其他人指出的那样,委托方法被调用,但仅在isEditableisfalse或用户点击并按住附件时才被调用。如果您想在编辑过程中了解简单的点击交互,请忘记它。

我沿着touchesBegan:hitTest:路径走下去,都有问题。touches 方法是在已经处理完交互之后调用的,粗暴了,因为它会混淆第一响应者的状态等等。UITextViewhitTest:

我最终的解决方案是手势识别器。Apple 正在内部使用这些,这就解释了为什么touchesBegan:一开始并不真正可行:手势识别器已经处理了这个事件。

我创建了一个新的手势识别器类,用于UITextView. 它只是检查水龙头的位置,如果它是附件,它会处理它。我使所有其他手势识别器都从属于我的手势识别器,因此我们首先查看事件,其他手势识别器只有在我们的手势识别器失败时才会发挥作用。

下面是手势识别器类,以及将其添加到UITextView. 我将它添加到我的UITextView子类中awakeFromNib,就像这样。(如果没有子类,则无需使用子类。)

override func awakeFromNib() {
    super.awakeFromNib()

    let recognizer = AttachmentTapGestureRecognizer(target: self, action: #selector(handleAttachmentTap(_:)))
    add(recognizer)

我通过调用现有UITextViewDelegate方法来处理该操作textView(_:,shouldInteractWith:,in:,interaction:)。您可以轻松地将处理代码直接放在操作中,而不是使用委托。

@IBAction func handleAttachmentTap(_ sender: AttachmentTapGestureRecognizer) {
    let _ = delegate?.textView?(self, shouldInteractWith: sender.attachment!, in: NSRange(location: sender.attachmentCharacterIndex!, length: 1), interaction: .invokeDefaultAction)
}

这里是主要课程。

import UIKit
import UIKit.UIGestureRecognizerSubclass

/// Recognizes a tap on an attachment, on a UITextView.
/// The UITextView normally only informs its delegate of a tap on an attachment if the text view is not editable, or a long tap is used.
/// If you want an editable text view, where you can short cap an attachment, you have a problem.
/// This gesture recognizer can be added to the text view, and will add requirments in order to recognize before any built-in recognizers.
class AttachmentTapGestureRecognizer: UIGestureRecognizer {

    /// Character index of the attachment just tapped
    private(set) var attachmentCharacterIndex: Int?

    /// The attachment just tapped
    private(set) var attachment: NSTextAttachment?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        attachmentCharacterIndex = nil
        attachment = nil

        let textView = view as! UITextView
        if touches.count == 1, let touch = touches.first, touch.tapCount == 1 {
            let point = touch.location(in: textView)
            let glyphIndex: Int? = textView.layoutManager.glyphIndex(for: point, in: textView.textContainer, fractionOfDistanceThroughGlyph: nil)
            let index: Int? = textView.layoutManager.characterIndexForGlyph(at: glyphIndex ?? 0)
            if let characterIndex = index, characterIndex < textView.textStorage.length {
                if NSAttachmentCharacter == (textView.textStorage.string as NSString).character(at: characterIndex) {
                    attachmentCharacterIndex = characterIndex
                    attachment = textView.textStorage.attribute(.attachment, at: characterIndex, effectiveRange: nil) as? NSTextAttachment
                    state = .recognized
                } else {
                    state = .failed
                }
            }
        } else {
            state = .failed
        }
    }
}

extension UITextView {

    /// Add an attachment recognizer to a UITTextView
    func add(_ attachmentRecognizer: AttachmentTapGestureRecognizer) {
        for other in gestureRecognizers ?? [] {
            other.require(toFail: attachmentRecognizer)
        }
        addGestureRecognizer(attachmentRecognizer)
    }

}

这种相同的方法大概可以用于链接上的点击。

于 2018-03-07T13:34:15.047 回答
3

斯威夫特 4.2

@objc func myMethodToHandleTap(_ sender: UITapGestureRecognizer) {

let myTextView = sender.view as! UITextView

     let layoutManager = myTextView.layoutManager

     // location of tap in myTextView coordinates and taking the inset into account
     var location = sender.location(in: myTextView)
     location.x -= myTextView.textContainerInset.left;
     location.y -= myTextView.textContainerInset.top;

     // character index at tap location
     let characterIndex = layoutManager.characterIndex(for: location, in: myTextView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)

     if characterIndex < myTextView.textStorage.length {

        let attributeValue = myTextView.attributedText.attribute(NSAttributedString.Key.attachment, at: characterIndex, effectiveRange: nil) as? NSTextAttachment

        if let _ = attributeValue {
           print("TAPPED ATTACHMENT")  
        }
     }

}
于 2020-06-09T19:28:05.250 回答
3

我已将 Drew 的手势识别器更改子类UITapGestureRecognizer而不是UIGestureRecognizer.

这提供了一个优点,即它只检测离散的轻击,而不是滚动的开始。

import UIKit
import UIKit.UIGestureRecognizerSubclass

// Modified from: https://stackoverflow.com/a/49153247/658604

/// Recognizes a tap on an attachment, on a UITextView.
/// The UITextView normally only informs its delegate of a tap on an attachment if the text view is not editable, or a long tap is used.
/// If you want an editable text view, where you can short cap an attachment, you have a problem.
/// This gesture recognizer can be added to the text view, and will add requirments in order to recognize before any built-in recognizers.
class AttachmentTapGestureRecognizer: UITapGestureRecognizer {

    typealias TappedAttachment = (attachment: NSTextAttachment, characterIndex: Int)

    private(set) var tappedState: TappedAttachment?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        tappedState = nil

        guard let textView = view as? UITextView else {
            state = .failed
            return
        }

        if let touch = touches.first {
            tappedState = evaluateTouch(touch, on: textView)
        }

        if tappedState != nil {
            // UITapGestureRecognizer can accurately differentiate discrete taps from scrolling
            // Therefore, let the super view evaluate the correct state.
            super.touchesBegan(touches, with: event)

        } else {
            // User didn't initiate a touch (tap or otherwise) on an attachment.
            // Force the gesture to fail.
            state = .failed
        }
    }

    /// Tests to see if the user has tapped on a text attachment in the target text view.
    private func evaluateTouch(_ touch: UITouch, on textView: UITextView) -> TappedAttachment? {
        let point = touch.location(in: textView)
        let glyphIndex: Int? = textView.layoutManager.glyphIndex(for: point, in: textView.textContainer, fractionOfDistanceThroughGlyph: nil)
        let index: Int? = textView.layoutManager.characterIndexForGlyph(at: glyphIndex ?? 0)
        guard let characterIndex = index, characterIndex < textView.textStorage.length else {
            return nil
        }
        guard NSTextAttachment.character == (textView.textStorage.string as NSString).character(at: characterIndex) else {
            return nil
        }
        guard let attachment = textView.textStorage.attribute(.attachment, at: characterIndex, effectiveRange: nil) as? NSTextAttachment else {
            return nil
        }
        return (attachment, characterIndex)
    }
}
于 2018-10-18T22:19:59.133 回答
2

斯威夫特 3 答案:

func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange) -> Bool {
    return true
}

确保您的 textView isEditable = falseisSelectable = trueisUserInteractionEnabled = true. 邓肯的回答没有提到isUserInteractionEnabled,这必须是true,否则它不会工作。

您可以通过编程方式(textView.isEditable = false)或通过属性检查器执行此操作: 在此处输入图像描述

在此处输入图像描述

于 2017-04-10T18:50:33.387 回答
0

使用 hitTest 在子类 UITextView 中获得触摸。这避免了弄乱标准编辑功能的问题。从位置获取字符索引,然后检查附件的字符。

于 2014-05-24T06:02:50.557 回答
0

我发现解决属性字符串中这种点击附件的常用方法是使用 UITextView 。但是 UITextView 非常复杂,无法禁用所有菜单、缩放等。所以我做了一个简单版本的 UILabel 包装器来支持附件点击。它简单易用,易于更改。演示在这里:

self.attachmentLabel.attributeText = attributeText;
self.attachmentLabel.numberOflines = 2;
self.attachmentLabel.selectBlock = ^(NSInteger attachmentIndex) {
    NSLog(@"attachment:%ld called",attachmentIndex);
};

https://github.com/ximmyxiao/TestAttributeStringClick

希望对你有帮助:)</p>

在此处输入图像描述

于 2021-11-04T08:20:22.650 回答