问题
I have NSTextView and I can have text as nsattributedstring. I can save text into .txt file using NSSavePanel, as plain text, but not as formatted text.
@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? What I should change in the code above, if I can use NSSavePanel for this ?
回答1:
One day out ... Ok, I have figured out the code for Swift 2 (note this - options: 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
{
}
}
回答2:
AppKit adds many methods to NSAttributedString. They are documented in the 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:
init(data:options:documentAttributes:)init(docFormat:documentAttributes:)init(RTF:documentAttributes:)init(RTFD:documentAttributes:)init(RTFDFileWrapper:documentAttributes:)
来源:https://stackoverflow.com/questions/33178895/how-can-i-save-the-attributed-string-text-into-file-swift-cocoa