目标是允许用户将NSImage
(s) 添加到 anNSAttributedString
中NSTextView
,然后反转该过程并提取图像。使用此处的代码,可以添加图像并内联显示它们。
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
}
}
}
}
我感谢有关如何从中提取图像的任何指导。谢谢你。