如何将属性字符串(文本)保存到文件(swift、cocoa)中?
我有NSTextView,可以将文本作为nsattributedstring。我可以使用NSSavePanel将文本以纯文本的形式保存到.txt文件中,但不能以格式化文本的形式保存如何将属性字符串(文本)保存到文件(swift、cocoa)中?,swift,cocoa,nsattributedstring,Swift,Cocoa,Nsattributedstring,我有NSTextView,可以将文本作为nsattributedstring。我可以使用NSSavePanel将文本以纯文本的形式保存到.txt文件中,但不能以格式化文本的形式保存 @IBAction func saveDNA(sender: AnyObject) { let saveDNAtoFile: NSSavePanel = NSSavePanel() saveDNAtoFile.canSelectHiddenExtension = true saveDNAto
@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将attributedstring(文本)保存到文件中,以便在格式化文本之前打开此文件?如果可以使用NSSavePanel,我应该在上面的代码中更改什么?AppKit为
NSAttributedString
添加了许多方法。它们记录在文档中。您感兴趣的是这些,用于转换为各种外部格式:
dataFromRange(\uuu:documentAttribute:)
fileWrapperFromRange(\uu:documentAttribute:)
docFormatFromRange(\uuquo:documentAttribute:)
RTFFromRange(uuquo;文档属性:)
RTFDFromRange(\uuu:documentAttribute:)
RTFDFileWrapperFromRange(uquo:DocumentAttribute:)
nsattributestring
的实例:
init(数据:选项:文档属性:)
init(docFormat:documentAttribute:)
init(RTF:documentAttribute:)
init(RTFD:documentAttribute:)
init(RTFDFileWrapper:documentAttribute:)
- 外出一天。。。好的,我已经找到了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
{
}
}
@IBAction func saveDNA(发送方:AnyObject)
{
让saveDNAtoFile:NSSavePanel=NSSavePanel()
saveDNAtoFile.canSelectHiddenExtension=true
saveDNAtoFile.runModal()
做
{
让exportedFileURL=saveDNAtoFile.URL
设textDNA=inputdnamuser.textStorage
如果exportedFileURL!=nil
{
让范围=NSRange(0..有一个AppKit/UIKit类别NSAttributedString
可以写RTF文本视图的textStorage
属性包含一个NSTextStorage
,而NSTextStorage
是NSMutableAttributedString
的一个子类。作为初学者,我一直认为像open和sav这样的标准功能在books和google中,标准文本文件应该到处都有标准代码。但事实并非如此。我有两本书《用Cocoa快速开发》还有OSX的Cocoa编程。没有这样清晰的代码示例。为什么?这很奇怪。你可以看看。使用下载链接获得整个Xcode项目。谢谢。但所有这些都是用Objective-C编写的,而不是swift。两个月前我从零开始学习swift,我不知道Objective-C。大多数Cocoa示例代码仍然是用Objective-C编写的目标C。你必须在阅读时感到舒适。