如何在macOS 10.14上检测到暗模式? [英] How can dark mode be detected on macOS 10.14?

查看:120
本文介绍了如何在macOS 10.14上检测到暗模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在macOS 10.14中,用户可以选择采用系统范围内的浅色或深色外观,我需要根据当前模式手动调整一些颜色.

In macOS 10.14 users can choose to adopt a system-wide light or dark appearance and I need to adjust some colours manually depend of the current mode.

推荐答案

由于您通常通过effectiveAppearance获得的实际外观对象是复合外观,因此直接询问其名称可能不是一个可靠的解决方案.

Since the actual appearance object you usually get via effectiveAppearance is a composite appearance, asking for its name directly probably isn't a reliable solution.

请求currentAppearance通常也不是一个好主意,因为视图可能被显式设置为亮模式,或者您想知道在drawRect:之外的视图是亮还是暗?模式切换后无法得到正确的结果.

Asking for the currentAppearance usually isn't a good idea, either, as a view may be explicitly set to light mode or you want to know whether a view is light or dark outside of a drawRect: where you might get incorrect results after a mode switch.

我想出的解决方案如下:

The solution I came up with looks like this:

BOOL appearanceIsDark(NSAppearance * appearance)
{
    if (@available(macOS 10.14, *)) {
        NSAppearanceName basicAppearance = [appearance bestMatchFromAppearancesWithNames:@[
            NSAppearanceNameAqua,
            NSAppearanceNameDarkAqua
        ]];
        return [basicAppearance isEqualToString:NSAppearanceNameDarkAqua];
    } else {
        return NO;
    }
}

您将像appearanceIsDark(someView.effectiveAppearance)一样使用它,因为如果明确设置了someView.appearance,则特定视图的外观可能会与另一个视图的外观不同.

You would use it like appearanceIsDark(someView.effectiveAppearance) since the appearance of a specific view may be different than that of another view if you explicitly set someView.appearance.

您还可以在NSAppearance上创建类别,并添加- (BOOL)isDark方法以获得someView.effectiveAppearance.isDark(最好选择一个Apple将来不太可能使用的名称,例如,通过添加供应商前缀).

You could also create a category on NSAppearance and add a - (BOOL)isDark method to get someView.effectiveAppearance.isDark (better chose a name that is unlikely to be used by Apple in the future, e.g. by adding a vendor prefix).

这篇关于如何在macOS 10.14上检测到暗模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆