[英]How can I save the attributed string (text) into file (swift, cocoa)?
我有NSTextView,我可以将文本作为nsattributedstring。 我可以使用NSSavePanel将文本保存为.txt文件,作为纯文本,但不是格式化文本。
@IBAction func saveDNA(sender: AnyObject)
{
let saveDNAtoFile: NSSavePanel = NSSavePanel()
saveDNAtoFile.canSelectHiddenExtension = true
saveDNAtoFile.runModal()
do
{
let exportedFileURL = saveDNAtoFile.URL
let textDNA = self.inputDnaFromUser.string
if exportedFileURL != nil
{
try textDNA!.writeToURL(exportedFileURL!, atomically: false, encoding: NSUTF8StringEncoding)
}
} catch
{
}
}
如何使用NSSavePanel将attributesstring(文本)保存到文件中,以便稍后能够在文本格式化之前打开此文件以使其全部生成? 如果我可以使用NSSavePanel,我应该在上面的代码中更改什么?
有一天...好吧,我已经找到了Swift 2的代码(注意这个 - 选项:NSFileWrapperWritingOptions.Atomic)。 下面。 我相信它会为像我这样的初学者节省时间,比这个标准功能更多时间来编写必要的和更有趣的算法。
@IBAction func saveDNA(sender: AnyObject)
{
let saveDNAtoFile: NSSavePanel = NSSavePanel()
saveDNAtoFile.canSelectHiddenExtension = true
saveDNAtoFile.runModal()
do
{
let exportedFileURL = saveDNAtoFile.URL
let textDNA = inputDnaFromUser.textStorage
if exportedFileURL != nil
{
let range = NSRange(0..<textDNA!.length)
let textTSave = try textDNA!.fileWrapperFromRange(range, documentAttributes: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType])
try textTSave.writeToURL(exportedFileURL!, options: NSFileWrapperWritingOptions.Atomic, originalContentsURL: nil)
}
} catch
{
}
}
AppKit为NSAttributedString
添加了许多方法。 它们记录在NSAttributedString AppKit Additions Reference中 。 您感兴趣的是转换为各种外部格式:
dataFromRange(_:documentAttributes:)
fileWrapperFromRange(_:documentAttributes:)
docFormatFromRange(_:documentAttributes:)
RTFFromRange(_:documentAttributes:)
RTFDFromRange(_:documentAttributes:)
RTFDFileWrapperFromRange(_:documentAttributes:)
这些,用于将这些外部格式转换回NSAttributedString
实例:
init(data:options:documentAttributes:)
init(docFormat:documentAttributes:)
init(RTF:documentAttributes:)
init(RTFD:documentAttributes:)
init(RTFDFileWrapper:documentAttributes:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.