【发布时间】:2019-10-02 21:14:39
【问题描述】:
我有一个 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 上设置内容和表示内容的单独图像。
【问题讨论】: