繁体   English   中英

如何将 PDF 附件插入 NSAttributedString 并在 UITextView 中显示

[英]How to insert a PDF attachment into NSAttributedString and display in a UITextView

我有一个 UITextView,我希望允许用户从照片库中插入照片和从文档选择器中插入 PDF。

将照片嵌入到文本视图属性字符串中非常容易:

        let attachment = NSTextAttachment(data: image.jpegData(1.0), ofType: kUTTypeJPEG as String)
        attachment.bounds = CGRect(origin: CGPoint.zero, size: CGSize(width: 40, height: 40))
        let attachmentString = NSAttributedString(attachment: attachment)
        let text = NSMutableAttributedString(attributedString: textView.attributedText)
        text.append(attachmentString)
        textView.attributedText = text

这非常适用于照片:图像显示在 UITextView 中,附件可从属性文本中检索:

            textView.attributedText.enumerateAttribute(.attachment, in: NSMakeRange(0, attributedText.length), options: []) { (item, range, ptr) in
            if let attachment = item as? NSTextAttachment {
                files.append(FileAttachment(data: attachment.contents, type: attachment.fileType))
            }

尝试附加 PDF 时出现问题。 如果我使用 PDF 遵循完全相同的模式,将数据替换为 PDF 数据并将文件类型替换为 kUTTypePDF,则会创建附件,但不会在 UITextView 中显示任何内容。

我应该能够简单地在 NSTextAttachment 上设置一个图像作为内容的表示,但这会重置附件数据。

        let data = Data(contentsOf: pdfURL)
        let attachment = NSTextAttachment(data: data, ofType: kUTTypePDF as String)
        attachment.image = UIImage(named: "pdf-document-icon")
        attachment.bounds = CGRect(origin: CGPoint.zero, size: CGSize(width: 40, height: 40))
        let attachmentString = NSAttributedString(attachment: attachment)
        let text = NSMutableAttributedString(attributedString: textView.attributedText)
        text.append(attachmentString)
        textView.attributedText = text

现在,PDF 附件在文本视图中显示为一个漂亮的图标,但后来当我枚举附件时,内容和文件类型为零。 即在 NSTextAttachment 上设置图像会重置内容和文件类型

我需要在 NSTextAttachment 上设置内容和表示内容的单独图像。

到目前为止,我想出的最好的解决方案是继承 NSTextAttachment:

class TextAttachmentWithThumbnail: NSTextAttachment {
    private var thumbnail: UIImage?

    override var image: UIImage? {
        get { return thumbnail }
        set { thumbnail = newValue }
    }
}

这样设置图像不再重置内容和文件类型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM