如何在 rtf 文件中写入 NSAttributedString?我找到了一个古老的答案如何将属性字符串(文本)保存到文件(swift、cocoa)中? https://stackoverflow.com/questions/33178895/how-can-i-save-the-attributed-string-text-into-file-swift-cocoa我不太明白我到底需要什么,也许某个地方存在新的不同方式?
您可以使用NSAttributedString
's 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)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)