【问题标题】:How to convert formatted content of NSTextView to string如何将 NSTextView 的格式化内容转换为字符串
【发布时间】:2013-04-26 13:13:22
【问题描述】:

我需要将 NSTextView 的内容从 Mac 应用程序传输到 iOS 应用程序。我使用 XML 作为传输文件格式。

所以我需要将 NSTextView 的内容(文本、字体、颜色等)保存为字符串。有什么办法吗?

【问题讨论】:

    标签: ios objective-c cocoa nstextview


    【解决方案1】:

    一种方法是归档 NSAttributedString 值。概述直接输入答案的示例代码:

    NSTextView *myTextView;
    NSString *myFilename;
    ...
    [NSKeyedarchiver archiveRootObject:myTextStorage.textStorage
                                toFile:myFilename];
    

    回读:

    myTextView.textStorage.attributedString = [NSKeyedUnarchiver unarchiveObjectWithFile:myFilename];
    

    这就是创建和读回文件所需的全部内容。有一些匹配的方法可以创建 NSData 而不是文件,您可以将 NSData 转换为 NSString 或将一个插入 NSDictionary 并将其序列化为 plist (XML) 等。

    【讨论】:

      【解决方案2】:

      您最好的选择可能是将文本存储为 RFTD,并通过 NSAttributedString 将其加载到其他文本视图中。

      // Load
      NSFileWrapper* filewrapper = [[NSFileWrapper alloc] initWithPath: path];
      NSTextAttachment *attachment = [[NSTextAttachment alloc] initWithFileWrapper: filewrapper];
      NSAttributedString* origFile = [NSAttributedString attributedStringWithAttachment: attachment];
      
      // Save
      NSData *data = [origFile RTFDFromRange: NSMakeRange(0, [origFile length]) documentAttributes: nil];
      [[NSFileManager defaultManager] createFileAtPath: path contents: data attributes:nil];
      

      【讨论】:

      • NSTextAttachment 在 iOS 上不可用,因此“加载”部分在那里不起作用。
      猜你喜欢
      • 2020-09-09
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      • 2021-09-25
      • 2013-02-19
      • 2013-09-22
      • 1970-01-01
      相关资源
      最近更新 更多