0

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.

Community
  • 1
  • 1
JKaz
  • 705
  • 6
  • 15
  • I gave a similar solution in Objective-C and iOS: http://stackoverflow.com/questions/29152660/extract-uiimage-from-nsattributed-string But I guess it may be applied (maybe with a few modifications for OS X). – Larme Nov 29 '16 at 08:57
  • What works in iOS for `UIImage` doesn't work for MacOS and `NSImage`, it seems. `image` is nil and `imageForBounds` returns what looks like a blank document icon. – JKaz Nov 29 '16 at 17:54
  • Does `z.content` have value? Or is there any property that aren't nil? – Larme Nov 29 '16 at 17:57
  • z.content is nil. Answer posted below. Thanks for contributing. In clicking around your link and links from that, somehow fell into the solution. – JKaz Nov 29 '16 at 18:03

1 Answers1

0

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
    }
}
JKaz
  • 705
  • 6
  • 15