2017-04-17 9 views

答えて

0

機能func enumerateAttribute(String, in: NSRange, options: NSAttributedString.EnumerationOptions = [], using: (Any?, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void)を使用して、属性NSAttachmentAttributeNameusing:ブロックを列挙し、最初の値を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 
関連する問題