我想在我的 NSTextVeiw / UITextView 中使用适应系统外观的文本颜色。深色模式,白色文本,否则黑色文本。我有以下 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
如果您只需要将属性字符串编码为数据,但并不特别需要它采用 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>";
})