You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS中NSAttributedString写入RTFD丢失自适应文本颜色求助

问题:iOS端RTFD保存/读取动态文本颜色失效,macOS正常

场景与代码实现

我需要在NSTextView/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

原本运行正常,但将文本保存为RTFD文档时,使用以下代码:

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端相同的效果,保存并读取RTFD文档后仍保留文本颜色的动态适配特性。

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 12:01:24