如何在NSTextView中从NSTextAttachment中提取NSImage?

时间:2016-11-29 05:52:07

标签: macos nsattributedstring nstextview nsimage nstextattachment

目标是允许用户将NSImage(s)添加到NSAttributedString中的NSTextView,然后撤消该过程并提取图像。使用here中的代码,可以添加图片并将其显示为内嵌。

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

我很欣赏有关如何从中提取图像的任何指导。谢谢。

1 个答案:

答案 0 :(得分:0)

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

中替换代码部分
if z != nil {
    let cell = z!.attachmentCell as? NSCell
    if cell != nil {
        let image = cell?.image
    }
}