How to pull NSImage from NSTextAttachment to NSTextView?

The goal is to allow the user to add NSImage (s) to an NSAttributedString in an NSTextView , and then cancel the process and extract the image (s). With the code here, you can add an image and display them in a line.

 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) 

It can deconstruct it to a valid (non-nil) NSTextAttachment , but it's unclear 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 advice on how to get an image out of this. Thanks.

0
nsattributedstring nstextview macos nsimage nstextattachment
source share
1 answer

Since NSImage was created using NSTextAttachmentCell , it must be extracted from the attachment cell. The key is to distinguish the cell as NSCell , and then capture the image property. So, replacing the code section with the original

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

All Articles