[英]How can I save the attributed string (text) into file (swift, cocoa)?
I have NSTextView and I can have text as nsattributedstring. 我有NSTextView,我可以将文本作为nsattributedstring。 I can save text into .txt file using NSSavePanel, as plain text, but not as formatted text. 我可以使用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
{
}
}
How can I save the attributedstring (text) into file using NSSavePanel, to be able later to open this file to have all made before formatting in the text? 如何使用NSSavePanel将attributesstring(文本)保存到文件中,以便稍后能够在文本格式化之前打开此文件以使其全部生成? What I should change in the code above, if I can use NSSavePanel for this ? 如果我可以使用NSSavePanel,我应该在上面的代码中更改什么?
One day out ... Ok, I have figured out the code for Swift 2 (note this - options: NSFileWrapperWritingOptions.Atomic). 有一天...好吧,我已经找到了Swift 2的代码(注意这个 - 选项:NSFileWrapperWritingOptions.Atomic)。 Below. 下面。 I am sure it will save time for beginners like me, more time to write necessary and more interesting algorithms, than this standard functionality. 我相信它会为像我这样的初学者节省时间,比这个标准功能更多时间来编写必要的和更有趣的算法。
@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 adds many methods to NSAttributedString
. AppKit为NSAttributedString
添加了许多方法。 They are documented in the NSAttributedString AppKit Additions Reference . 它们记录在NSAttributedString AppKit Additions Reference中 。 Of interest to you are these, for converting to various external formats: 您感兴趣的是转换为各种外部格式:
dataFromRange(_:documentAttributes:)
fileWrapperFromRange(_:documentAttributes:)
docFormatFromRange(_:documentAttributes:)
RTFFromRange(_:documentAttributes:)
RTFDFromRange(_:documentAttributes:)
RTFDFileWrapperFromRange(_:documentAttributes:)
and these, for converting those external formats back to instances of NSAttributedString
: 这些,用于将这些外部格式转换回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.