我有一个 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/