如何解决如何在 rtf 文件中写入 NSAttributedString?
如何在 rtf 文件中写入 NSAttributedString?我找到了一个古老的答案How can I save the attributed string (text) into file (swift,cocoa)? 我不太明白我到底需要什么,也许某处存在新的不同方式?
解决方法
您可以使用 NSAttributedString
的 data(from:)
方法将您的属性字符串转换为 rtf 数据。
extension NSAttributedString {
func rtf() throws -> Data {
try data(from: .init(location: 0,length: length),documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf,.characterEncoding: String.Encoding.utf8])
}
}
let textView = UITextView()
textView.attributedText = .init(string: "abc",attributes: [.font: UIFont(name: "Helvetica",size: 16)!])
do {
let rtfURL = try FileManager.default.url(for: .documentDirectory,in: .userDomainMask,appropriateFor: nil,create: false).appendingPathComponent("RichTextDocument.rtf")
try textView.attributedText.rtf().write(to: rtfURL)
print("saved")
} catch {
print(error)
}
,
Swift 4
do {
let attributedString = try NSAttributedString(url: fileURL,options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf],documentAttributes: nil)
} catch {
print("\(error.localizedDescription)")
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。