【问题标题】:How to get the image name of an NSTextAttachment from NSAttributedString如何从 NSAttributedString 获取 NSTextAttachment 的图像名称
【发布时间】:2017-04-15 17:41:53
【问题描述】:

我有一个 Mac 应用程序,它可以读取带有存储为 NSAttributedString 的图像的格式化文本。我想将其转换为 HTML,包括图像。

获取 HTML 工作正常,我什至可以枚举附加图像,但无法获取附加图像的实际文件名。我需要那些用于生成的 HTML。

获取 HTML:

let htmlData = try attrString.dataFromRange(NSMakeRange(0, attrString.length), 
documentAttributes: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType])

产生:

<p class="p1"><img src="file:///Untitled%202.jpg" alt="Untitled 2.jpg"></p>

枚举附加图像:

    attrString.enumerateAttribute(NSAttachmentAttributeName,
        inRange: NSMakeRange(0, attrString.length),
        options: [],
        usingBlock: {attachment, range, _ in

        if let attachment = attachment as? NSTextAttachment,
            let fileWrapper = attachment.fileWrapper,
            let data = fileWrapper.regularFileContents
        {
            // This prints <NSTextAttachment: 0x7fe68d5304c0> "Untitled 2.jpg"
            // But there's no API to get the name?
            print(attachment.description)
        }
    })

所以我最终得到了NSTextAttachment 实例,但无法确定实际文件名(“Untitled 2.jpg”)。 NSFileWrapper.filename 返回 nil,我没有看到从文本附件中获取名称的 API。

令人沮丧的部分是信息在文本附件中。如果我打印它的调试描述,我会看到文件名:

<NSTextAttachment: 0x7fe68d5304c0> "Untitled 2.jpg"
<NSTextAttachment: 0x7fe68d533d60> "Pasted Graphic.tiff"

如何访问文件名? (不解析调试描述;)

【问题讨论】:

  • fileWrapper.preferredFilename?

标签: cocoa nsattributedstring nstextattachment


【解决方案1】:

NSTextAttachment 没有图像名称和图像 url 的属性,这绝对是荒谬的。

我在初始化自定义类时继承了 NSTextAttachment 并添加了这些属性。

例如:

子类:

import Foundation

class CustomTextAttachment: NSTextAttachment {

    var imageURL: String?
    var imageTitle: String?

}

实施:

let textAttachment = CustomTextAttachment()
textAttachment.imageTitle = title
textAttachment.imageURL = url

现在当我点击图片时:

func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange) -> Bool {

    print("Tapped custom text attachment")

    if let commentTextAttachment = textAttachment as? CustomTextAttachment, let title = commentTextAttachment.imageTitle, let link = commentTextAttachment.imageURL {
         print("Got title \(title) and link \(link) for attachment")
    }

    return true
}

【讨论】:

    【解决方案2】:

    供将来参考:使用fileWrapper.preferredFilename 而不是fileWrapper.fileName(感谢@Willeke)。谁会想到有两个属性...

    【讨论】:

      猜你喜欢
      • 2015-02-01
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多