且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在macOS 10.14上检测到暗模式?

更新时间:2023-12-04 18:51:22

由于您通常通过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).