【问题标题】:Swift conversion of NSColor.textColor to cgColor ignores theme将 NSColor.textColor 快速转换为 cgColor 会忽略主题
【发布时间】:2021-07-06 19:13:34
【问题描述】:

从 macOS Big Sur 开始,系统的菜单栏根据壁纸具有不同的内容颜色(不再取决于暗/亮模式)。一般来说,使用该颜色很容易,因为NSColor.textColor 是当前使用的文本颜色。但是,当使用背景颜色时,需要将其转换为 CGColor,这似乎不支持这种“实时更新”。

我尝试了以下方法:

let contentColor = NSColor.textColor // black/white at this point
contentColor.cgColor // always white at his point

如何将实际计算的 NSColor 转换为 CGColor?

【问题讨论】:

    标签: swift xcode macos


    【解决方案1】:

    CGColorCALayer 不理解 AppKit 和 UIKit 概念中的动态颜色。您需要手动处理。所以这将有两个阶段:

    检测变化

    观察某处的变化

    DistributedNotificationCenter.default.addObserver(self, selector: #selector(interfaceModeChanged(notification:)), name: NSNotification.Name(rawValue: "AppleInterfaceThemeChangedNotification"), object: nil)
    

    应用更改

    @objc func interfaceModeChanged(notification: NSNotification) {
        switch view.effectiveAppearance.name {
        case .darkAqua: print("Set a Dark Color")
        default: print("Handle other states here")
        }
    }
    

    请注意,AppKit 中有很多 NSAppearance.Names。因此,您可能需要确保正确处理所有情况。

    【讨论】:

    • 感谢您的回复!一般来说,这工作正常,但似乎只考虑系统主题/模式而不考虑菜单栏。当改变壁纸和菜单栏外观改变时,view.effectiveAppearance 仍然是一样的。
    • 也许您应该搜索 detecting 您想要的更改并在那里执行 apply 部分
    • 我设法修复了它,问题是我使用了视图的有效外观而不是状态项的按钮。后者可以正常工作,并根据壁纸在“NSAppearanceNameVibrantDark”和“NSAppearanceNameVibrantLight”之间切换。
    • statusItem.addObserver(self, forKeyPath: "button.effectiveAppearance", options: NSKeyValueObservingOptions.new, context: nil) 用于检测壁纸变化
    猜你喜欢
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多