【问题标题】:Transform an NSAttributedString to plain text将 NSAttributedString 转换为纯文本
【发布时间】:2019-09-19 03:02:45
【问题描述】:

我有一个 NSData 实例,其中包含源自 NSTextView 的属性文本 (NSAttributedString)。我想将属性字符串转换为纯字符串 (NSString) 而不进行任何格式的文本分析(在转换时我无法访问原始 NSTextView 及其 NSTextStorage 实例)。

最好的方法是什么?

编辑:

出于好奇,我检查了以下结果:

[[[self textView] textStorage] words]

这对于进行一些文本分析似乎很方便。生成的数组包含 NSSubTextStorage 的实例(下面是“Eastern”一词的示例):

东部{ NSFont = "\"LucidaGrande 11.00 pt。 P [] (0x7ffcaae08330) fobj=0x10a8472d0, spc=3.48\""; NSParagraphStyle = "对齐 0, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0,制表符(\n 28L,\n 56L,\n 84L,\n 112L,\n
140L,\n 168L,\n 196L,\n 224L,\n 252L,\n 280L,\n
308L,\n 336L\n), DefaultTabInterval 0, 块 (null), 列表 (null), BaseWritingDirection -1,HyphenationFactor 0,TighteningFactor 0.05, 标头级别 0"; }

NSSubTextStorage 可能是一个私有类,因为我找不到它的任何文档。它还保留所有格式。

【问题讨论】:

    标签: cocoa nsattributedstring


    【解决方案1】:

    如果我对您的理解正确,您有一个NSData,比如data,其中包含一个编码的NSAttributedString。要反转该过程:

    NSAttributedString *nas = [[NSAttributedString alloc] initWithData:data
                                                               options:nil
                                                    documentAttributes:NULL
                                                                 error:NULL];
    

    然后获取没有属性的纯文本:

    NSString *str = [nas string];
    

    【讨论】:

    • 哦,天哪...我必须出去呼吸一下新鲜空气。感谢你的回答!不敢相信我自己没看到……[self kick]
    • 如果属性屏幕中存在图像附件,结果字符串属性将返回一个?在那个附件的地方。我正在努力寻找解决方案。有什么想法可以分享一下吗?
    • @Avi - 你可能看到的是NSAttachmentCharacter,如果是这样,你可以简单地删除它的任何出现。它被记录为NSTextAttachment 的一部分。
    【解决方案2】:

    为 Swift 5 更新:

    attributedText.string
    

    【讨论】:

      【解决方案3】:

      对于 Swift 5 和 macOS 10.0+,NSAttributedString 有一个名为 string 的属性。 string 有以下声明:

      var string: String { get }
      

      作为NSString对象的接收者的字符内容。

      苹果还声明了string

      附件字符不会从此属性的值中删除。 [...]


      以下 Playground 代码展示了如何使用NSAttributedStringstring 属性来检索NSAttributedString 实例的字符串内容:

      import Cocoa
      
      let string = "Some text"
      let attributes = [NSAttributedString.Key.underlineStyle : NSUnderlineStyle.single]
      let attributedString = NSAttributedString(string: string, attributes: attributes)
      
      /* later */
      
      let newString = attributedString.string
      print(newString) // prints: "Some text"
      print(type(of: newString)) // prints: String
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-12
        • 2014-09-08
        • 2020-08-27
        • 2010-11-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多