识别标签中显示的属性字符串中的图像点按



我有一个属性字符串

,如下所示,显示在标签中。
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

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

  • 创建一个新的 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)

然后在 Tap 操作调用的函数中:

@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)")
}
}
}

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

最新更新