Search code examples
macosnsattributedstringnstextviewnsimagenstextattachment

How to pull NSImage from NSTextAttachment in NSTextView?


Goal is to allow user to add NSImage(s) to an NSAttributedString in an NSTextView, and then reverse the process and extract the image(s). With code from here, can add image(s) and have them displayed inline.

let attributedText = NSMutableAttributedString(string: string, attributes: attributes as? [String : AnyObject])

let attachment = NSTextAttachment()
let imageTest = NSImage(named:"sampleImage") as NSImage?
let attachmentCell: NSTextAttachmentCell = NSTextAttachmentCell.init(imageCell: imageTest)
attachment.attachmentCell = attachmentCell
let imageString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
attributedText.append(imageString)
textView.textStorage?.setAttributedString(attributedText)

Can deconstruct this as far as a legit (non-nil) NSTextAttachment, but uncertain how to extract the image.

if (textView.textStorage?.containsAttachments ?? false) {
    let runs = textView.textStorage?.attributeRuns
    if runs != nil {
        for run in runs! {
            var r = NSRange()
            let att = run.attributes(at: 0, effectiveRange: &r)
            let z = att[NSAttachmentAttributeName] as? NSTextAttachment
            if z != nil {
                Swift.print(z!)
                // z!.image and z!.contents are both nil
            }
        }
    }
}

I appreciate any guidance on how to pull the image(s) from this. Thank you.


Solution

  • Since the NSImage was created with an NSTextAttachmentCell, it must be retrieved from the attachment cell. The key is to cast the cell as NSCell and then grab the image property. So, replacing the section of code from the original

    if z != nil {
        let cell = z!.attachmentCell as? NSCell
        if cell != nil {
            let image = cell?.image
        }
    }