iOS中如何保存UITextView里的图片与文本?
解决方案:用Documents目录保存带图片的富文本
核心思路
UITextView里的图片是通过NSTextAttachment嵌入到富文本(NSAttributedString)中的,直接保存text属性会丢失图片信息。我们需要把完整的富文本以RTF格式写入Documents目录,读取时再还原成富文本。
步骤1:定义文件存储路径
添加工具方法获取Documents目录下的笔记文件路径:
private func noteFileURL() -> URL { let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! return documentsDirectory.appendingPathComponent("userNote.rtf") }
步骤2:修改保存逻辑
替换原来的saveText方法,将富文本转为RTF数据写入文件:
@objc func saveText() { do { // 将富文本转为RTF格式数据 let rtfRange = NSRange(location: 0, length: textView.attributedText.length) let rtfData = try textView.attributedText.data(from: rtfRange, documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf]) // 写入Documents目录 try rtfData.write(to: noteFileURL()) dismiss(animated: true, completion: nil) } catch { print("保存笔记失败: \(error.localizedDescription)") } }
步骤3:修改读取逻辑
在viewDidLoad中替换原UserDefaults读取逻辑,改为从Documents读取RTF数据并还原富文本:
override func viewDidLoad() { super.viewDidLoad() textView.delegate = self self.isModalInPresentation = true textView.keyboardDismissMode = .interactive textView.becomeFirstResponder() // 保留你原来的文本样式设置 textView.textColor = UIColor(red: 222/255, green: 215/255, blue: 191/255, alpha: 1.0) textView.font = UIFont(name: "Trebuchet MS", size: 19) textView.backgroundColor = UIColor.clear textView.tintColor = UIColor(red: 141/255, green: 124/255, blue: 85/255, alpha: 1.0) textView.layer.masksToBounds = false textView.alwaysBounceVertical = true // 读取保存的富文本 if FileManager.default.fileExists(atPath: noteFileURL().path) { do { let rtfData = try Data(contentsOf: noteFileURL()) let attributedText = try NSAttributedString(data: rtfData, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil) textView.attributedText = attributedText } catch { print("读取笔记失败: \(error.localizedDescription)") } } }
为什么不用UserDefaults?
UserDefaults仅适合存储轻量配置数据(如开关状态、用户偏好),存储包含图片的大体积富文本会引发性能问题,且不符合苹果官方的使用规范。Documents目录是沙盒中专门用于存储用户生成内容的目录,完全匹配这类场景需求。
内容的提问来源于stack exchange,提问作者Dian
相关产品推荐
相关产品推荐

