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.