ios - into - Extract UIImage from NSAttributed String



nstextattachment uiview (2)

What I am doing is:

  1. NSATTRIBUTE STRING = NSSTRING + UIIMAGE's;
  2. NSDATA = NSATTRIBUTED STRING;
  3. ALSO I am able to convert nsdata to nsattributed string
  4. NSATTRIBUTED STRING = NSDATA:
  5. And then extracting nesting from NSAttributed string
  6. NSSTRING = [NSATTRIBUTED STRING string];

Query:

How can i get IMAGES from NSATTRIBUTED STRING;

  • UIIMAGE = from NSATTRIBUTED STRING;
  • ARRAYOFIMAGE = from NSATTRIBUTED STRING;

https://src-bin.com


Answer #1

I converted the code Larme to swift 3

      var imagesArray = [Any]()

      textView.attributedText.enumerateAttribute(NSAttachmentAttributeName, in: NSRange(location: 0, length: textView.attributedText.length), options: [], using: {(value,range,stop) -> Void in
            if (value is NSTextAttachment) {
                let attachment: NSTextAttachment? = (value as? NSTextAttachment)
                var image: UIImage? = nil

                if ((attachment?.image) != nil) {
                    image = attachment?.image 
                } else {
                    image = attachment?.image(forBounds: (attachment?.bounds)!, textContainer: nil, characterIndex: range.location)
                }

                if image != nil {
                  imagesArray.append(image)
                }
            }
        })

Answer #2

In Swift 3: (with macOS equivalent here )

func textViewDidChange(_ textView: UITextView) {

    // other code...

    let range = NSRange(location: 0, length: textView.attributedText.length)
    if (textView.textStorage.containsAttachments(in: range)) {
        let attrString = textView.attributedText
        var location = 0
        while location < range.length {
            var r = NSRange()
            let attrDictionary = attrString?.attributes(at: location, effectiveRange: &r)
            if attrDictionary != nil {
                // Swift.print(attrDictionary!)
                let attachment = attrDictionary![NSAttachmentAttributeName] as? NSTextAttachment
                if attachment != nil {
                    if attachment!.image != nil {
                        // your code to use attachment!.image as appropriate
                    }
                }
                location += r.length
            }
        }
    }
}




nsattributedstring