0

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

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

我感谢有关如何从中提取图像的任何指导。谢谢你。

4

1 回答 1

0

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

if z != nil {
    let cell = z!.attachmentCell as? NSCell
    if cell != nil {
        let image = cell?.image
    }
}
于 2016-11-29T18:01:40.893 回答