如何检查NSAttributedString是否包含任何带有图像的NSTextAttachment?
发布于 2017-04-17 21:32:01
您可以使用函数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) //truehttps://stackoverflow.com/questions/43452350
复制相似问题