簡體   English   中英

如何將屬性字符串(文本)保存到文件中(swift,cocoa)?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM