I need to use textual content colour in my NSTextVeiw / UITextView that adapts to the system look. Darkish mode, white textual content, in any other case black textual content. I’ve the next NSAttributedString:
#if os(iOS)
let testAttributedString = NSAttributedString(string: "Check", attributes: [NSAttributedString.Key.foregroundColor: UIColor.label])
#elseif os(macOS)
let testAttributedString = NSAttributedString(string: "Check", attributes: [NSAttributedString.Key.foregroundColor: NSColor.textColor])
#endif
So I take advantage of UIColor.label
on iOS and NSColor.textColor
on macOS. That works effectively, nevertheless I’ve to avoid wasting the typed textual content so I create an RTF
doc:
textData = strive! testAttributedString.information(from: NSMakeRange(0, testAttributedString.size), documentAttributes: [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.rtfd])
For some purpose on iOS the textual content colour is being transformed to pure black (or pure white if darkish mode is on). On macOS nevertheless, the dynamic colour is being saved and likewise returned if I learn the info again utilizing:
let testAttributedStringFromData = strive! NSAttributedString(information: textData!, choices: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtfd], documentAttributes: nil)
If I print the colour utilizing attributedString.attributes(at: 0, effectiveRange: nil)[.foregroundColor]
, I get the next outcomes:
-
on iOS:
- earlier than writing:
<UIDynamicCatalogSystemColor: 0x600003ca6c40; identify = labelColor>
- after studying:
kCGColorSpaceModelMonochrome 1 1
- earlier than writing:
-
on macOS:
- earlier than writing:
Catalog colour: System textColor
- after studying:
Catalog colour: System textColor
- earlier than writing:
I need the identical behaviour from macOS on iOS.
I’ve created a small pattern so that you can take a look at right here: https://github.com/Iomegan/Persist-Adaptive-Textual content-Colour