如何从NSTextView中的NSTextAttachment中拉出NSImage? [英] How to pull NSImage from NSTextAttachment in NSTextView?

查看:213
本文介绍了如何从NSTextView中的NSTextAttachment中拉出NSImage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是允许用户将NSImage添加到NSTextView中的NSAttributedString中,然后反转该过程并提取图像.使用此处中的代码,可以添加图像),并使其内联显示.

Goal is to allow user to add NSImage(s) to an NSAttributedString in an NSTextView, and then reverse the process and extract the image(s). With code from here, can add image(s) and have them displayed inline.

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)

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

Can deconstruct this as far as a legit (non-nil) NSTextAttachment, but uncertain how to extract the image.

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

我非常感谢您提供有关如何从中提取图像的指导.谢谢.

I appreciate any guidance on how to pull the image(s) from this. Thank you.

推荐答案

由于NSImage是用NSTextAttachmentCell创建的,因此必须从附件单元中检索它.关键是将单元格强制转换为NSCell,然后获取image属性.因此,替换原始代码中的代码部分

Since the NSImage was created with an NSTextAttachmentCell, it must be retrieved from the attachment cell. The key is to cast the cell as NSCell and then grab the image property. So, replacing the section of code from the original

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

这篇关于如何从NSTextView中的NSTextAttachment中拉出NSImage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆