目标是允许用户将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
}
}
}
}
我很欣赏有关如何从中提取图像的任何指导。谢谢。
答案 0 :(得分:0)
由于NSImage
是使用NSTextAttachmentCell
创建的,因此必须从附件单元格中检索它。关键是将单元格转换为NSCell
,然后获取image
属性。所以,从原来的
if z != nil {
let cell = z!.attachmentCell as? NSCell
if cell != nil {
let image = cell?.image
}
}