如何判断NSAttributedString是否包含图像?

时间:2017-04-17 13:21:43

标签: ios nsattributedstring

如何检查NSAttributedString是否包含带有图片的NSTextAttachment个?

1 个答案:

答案 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
相关问题