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

标签 ios swift

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

将照片嵌入到 TextView 属性字符串中非常容易:

        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 附件在 TextView 中显示为一个漂亮的图标,但稍后当我枚举附件时,内容和文件类型为零。即在 NSTextAttachment 上设置图像会重置内容和文件类型

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

最佳答案

到目前为止我想出的最好的解决方案是子类化 NSTextAttachment:

class TextAttachmentWithThumbnail: NSTextAttachment {
    private var thumbnail: UIImage?

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

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

关于ios - 如何将 PDF 附件插入 NSAttributedString 并显示在 UITextView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209451/

相关文章:

ios - 在 iOS 上获取相机当前曝光持续时间值?

ios - 如何在 URLSession 数据任务中设置变量?

swift - 无法将 Double 转换为预期的参数类型 CGFloat

html - 如何更改 WKWebView 文本颜色?

ios - 只为 iPad 设置横向方向而不是 iPhone

在 Xcode 中找不到 iostream

iphone - ios - 使强调的字符在文件路径中很好地显示

ios - 匹配字符串中的<a> anchor 标记,提取其 `href`

ios - 如何从具有多个单元格原型(prototype)的 UITableView 中捕获单元格数据?

ios - 如何在 XCode 7 中恢复到 iOS SDK 8?