iOS:NSAttributedString -写入数据会丢失自适应文本颜色

qfe3c7zg  于 11个月前  发布在  iOS
关注(0)|答案(1)|浏览(82)

我想在我的NSTextVeiw /NSTextView中使用适应系统外观的文本颜色。深色模式,白色文本,否则为黑色文本。我有以下NSAttributedString:

#if os(iOS)
    let testAttributedString = NSAttributedString(string: "Test", attributes: [NSAttributedString.Key.foregroundColor: UIColor.label])
#elseif os(macOS)
    let testAttributedString = NSAttributedString(string: "Test", attributes: [NSAttributedString.Key.foregroundColor: NSColor.textColor])
#endif

字符串
所以我在iOS上使用UIColor.label,在macOS上使用NSColor.textColor。这很好用,但是我必须保存键入的文本,所以我创建了一个RTF文档:

textData = try! testAttributedString.data(from: NSMakeRange(0, testAttributedString.length), documentAttributes: [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.rtfd])


由于某种原因,在iOS上,文本颜色被转换为纯黑色(或纯白色,如果黑暗模式打开)。然而,在macOS上,动态颜色被保存,如果我使用以下命令读取数据,也会返回:

let testAttributedStringFromData = try! NSAttributedString(data: textData!, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtfd], documentAttributes: nil)


如果我使用attributedString.attributes(at: 0, effectiveRange: nil)[.foregroundColor]打印颜色,我会得到以下结果:

*在iOS上:

  • 写之前:<UIDynamicCatalogSystemColor: 0x600003ca6c40; name = labelColor>
  • 阅读后:kCGColorSpaceModelMonochrome 1 1
    *在macOS上:
  • 写之前:Catalog color: System textColor
  • 阅读后:Catalog color: System textColor

我希望iOS上的macOS也有同样的行为。
我创建了一个小样本供您测试:https://github.com/Iomegan/Persist-Adaptive-Text-Color

ohfgkhjo

ohfgkhjo1#

如果您只需要将属性化字符串编码为数据,但不特别需要它是RTF格式,那么可以使用NSKeyedArchiver存档字符串。

let testAttributedString = NSAttributedString(string: "Test", attributes: [NSAttributedString.Key.foregroundColor: UIColor.label])
print(testAttributedString)
do {
    let data = try NSKeyedArchiver.archivedData(withRootObject: testAttributedString, requiringSecureCoding: true)
    let newStr = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSAttributedString.self], from: data)
    print(newStr)
} catch {
    print(error)
}

字符串
这给出了输出:

Test{
    NSColor = "<UIDynamicCatalogSystemColor: 0x600001714780; name = labelColor>";
}
Optional(Test{
    NSColor = "<UIDynamicCatalogSystemColor: 0x600001714780; name = labelColor>";
})

相关问题