如何从 NSTextView 中的 NSTextAttachment 拉取 NSImage?

How to pull NSImage from NSTextAttachment in NSTextView?

目标是允许用户将 NSImage(s) 添加到 NSTextView 中的 NSAttributedString,然后反转过程并提取图像。使用 中的代码,可以添加图像并内联显示它们。

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)

可以将其解构为合法(非零)NSTextAttachment,但不确定如何提取图像。

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

我很感激任何关于如何从中提取图像的指导。谢谢。

由于 NSImage 是使用 NSTextAttachmentCell 创建的,因此必须从附件单元格中检索它。关键是将单元格转换为 NSCell,然后获取 image 属性。所以,替换掉原来的那段代码

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