首页 > 解决方案 > 识别标签中显示的属性字符串中的图像点击

问题描述

我有一个如下的属性字符串要显示在标签中。

let someText = NSMutableAttributedString(string: "This is a sample text with")
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named: "icon") 

let imageString = NSAttributedString(attachment: imageAttachment)
someText.append(imageString)
someText.append(NSAttributedString(string: "attached")
somelabel.attributedText = someText

标签显示This is a sample text with 'image' attached

如何识别点击图像(而不是文本)以执行操作?

标签: iosswiftxcodeuilabelnsmutableattributedstring

解决方案


  • 创建一个新的 NSAttributedStringKey 用于识别图像附件。
  • 然后使用图像创建一个 NSTextAttachment,将其包装在 NSMutableAttributedString 中,并为其添加自定义属性。
  • 最后将包装器添加到完整的 NSAttributedString 并附加一个 UITapGestureRecognizer。

  • 然后,当在 UITapGestureRecognizer 上的选择器中时,只需查找该自定义标记。

大多数代码:

extension NSAttributedStringKey {
static let imagePath = NSAttributedStringKey(rawValue: "imagePath")
}

何时设置文本显示

let fullString = NSMutableAttributedString()    
let imageAttachment = NSTextAttachment()
imageAttachment.image = image

let imageAttributedString: NSMutableAttributedString = NSAttributedString(attachment: imageAttachment).mutableCopy() as! NSMutableAttributedString

let customAttribute = [ NSAttributedStringKey.imagePath: imagePath ]
imageAttributedString.addAttributes(customAttribute, range: NSRange(location: 0, length: imageAttributedString.length))

fullString.append(imageAttributedString)

然后在点击动作调用的函数中:

    @objc func onImageTap(_ sender: UITapGestureRecognizer) {
      let textView = sender.view as! UITextView
      let layoutManager = textView.layoutManager

      // location of tap in textView coordinates
      var location = sender.location(in: textView)
      location.x -= textView.textContainerInset.left;
      location.y -= textView.textContainerInset.top;

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

      // if index is valid 
      if characterIndex < textView.textStorage.length {

        // check if the tap location has the custom attribute
        let attributeValue = textView.attributedText.attribute(NSAttributedStringKey.imagePath, at: characterIndex, effectiveRange: nil) as? String
        if let value = attributeValue {
            print("You tapped on \(NSAttributedStringKey.imagePath) and the value is: \(value)")
        }

    }

}

从那里您知道点击在图像中,并且您在图像框架内有坐标,因此您可以使用该组合来确定图像中的点击位置。


推荐阅读