在黑暗模式下,NSTextView在几乎黑色的黑色上绘制黑色

问题描述 投票:9回答:3

当我在暗模式下构建我的macOS应用程序时,我的一些文本视图(NSTextView)在几乎黑色的背景上呈现黑色文本。在Interface Builder中,在Attributes Inspector中,“Text Color”设置为系统“Default(Text Color)”,我认为这是正确的。实际上,在Interface Builder中,根据需要,此文本在暗模式下呈现白色,在光模式下呈现黑色。我搜索了我的代码中的任何行,我可能会在此视图中将文本颜色设置为黑色,但找不到任何行。为什么我的文字总是黑的?

cocoa nstextview macos-darkmode
3个回答
6
投票

我注意到错误的文本视图将其“属性字符串”与Cocoa Bindings绑定到返回普通的NSString对象的方法。我可能这样做是因为我多年前写这个应用程序时很懒,而且效果很好。这种不匹配证明是问题所在。修复方法是修改这些方法以返回NSAttributedString,其中包含键/值对的属性字典

NSForegroundColorAttributeName : NSColor.controlTextColor

可能发生的事情是,当一个属性字符串绑定获得非属性字符串时,Cocoa被设计为执行您可能想要的操作。 Cocoa不是禁止异常,而是应用一些“默认”属性,其中包括自1984年以来一直是macOS默认的黑色文本颜色 - 在Dark Mode出现之前完全合情合理!好吧,苹果将这个默认值从黑色更改为controlTextColor可能不错,但显然他们没有。

结论:我们无法再将文本视图的属性字符串绑定到普通的非属性字符串。


4
投票

如果您在NSTextView中使用纯文本(例如,因为您需要scrollview),只需绑定到value属性而不是attributedString。此绑定将使用控件的文本颜色设置,并与Dark Mode完美配合。


0
投票

NSTextView扩展名为“普通”(非属性)字符串。适用于浅色或深色模式:

extension NSTextView {
    static let DefaultAttribute =
        [NSAttributedString.Key.foregroundColor: NSColor.textColor] as [NSAttributedString.Key: Any]

    var stringValue: String {
        return textStorage?.string ?? ""
    }

    func setString(_ string: String) {
        textStorage?.mutableString.setString("")
        append(string)
    }

    func append(_ string: String) {
        let attributedText = NSAttributedString(string: string, attributes: NSTextView.DefaultAttribute)
        textStorage?.append(attributedText)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.