如何检查NSAttributedString
是否包含带有图片的NSTextAttachment
个?
答案 0 :(得分:0)
您可以使用函数func enumerateAttribute(String, in: NSRange, options: NSAttributedString.EnumerationOptions = [], using: (Any?, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void)
枚举属性NSAttachmentAttributeName
,并将using:
块强制转换为NSTextAttachment,并检查它是否有图像。
extension NSAttributedString {
var hasImage: Bool {
var hasImage = false
let fullRange = NSRange(location: 0, length: self.length)
self.enumerateAttribute(NSAttachmentAttributeName, in: fullRange, options: []) { (value, _, _) in
print(value)
guard let attachment = value as? NSTextAttachment else { return }
if let _ = attachment.image {
hasImage = true
}
}
return hasImage
}
}
let stringWithoutAttachment = NSAttributedString(string: "Some string")
print(stringWithoutAttachment.hasImage) //false
let attachment = NSTextAttachment()
attachment.image = UIImage()
let stringWithAttachment = NSAttributedString(attachment: attachment)
print(stringWithAttachment.hasImage) //true