How to pull NSImage from NSTextAttachment in NSTextView?

和自甴很熟 提交于 2020-03-06 09:12:55

问题


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.


回答1:


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
    }
}


来源:https://stackoverflow.com/questions/40858674/how-to-pull-nsimage-from-nstextattachment-in-nstextview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!