简体   繁体   中英

How to detect if OSX in dark or light mode in Auto Appearance Mode in Catalina

My Mac app needs to change behaviour depending on light or dark mode.

Whats the best way to detect style when Appearance option is selected to auto in macOS Catalina?

NSDictionary *dict = [[NSUserDefaults standardUserDefaults] persistentDomainForName:NSGlobalDomain];
id style = [dict objectForKey:@"AppleInterfaceStyle"];

BOOL darkModeOn = ( style && [style isKindOfClass:[NSString class]] && NSOrderedSame == [style caseInsensitiveCompare:@"dark"] );

darkModeOn is still yes/dark even after switching from dark to auto appearance option.

you need to combine AppleInterfaceStyle with this new value introduced in macOS Catalina AppleInterfaceStyleSwitchesAutomatically .

Here is some pseudo-code explaining how to:

theme = light //default is light
if macOS_10.15
    if UserDefaults(AppleInterfaceStyleSwitchesAutomatically) == TRUE
        if UserDefaults(AppleInterfaceStyle) == NIL
            theme = dark // is nil, means it's dark and will switch in future to light
        else
            theme = light //means it's light and will switch in future to dark
        endif
    else
        if UserDefaults(AppleInterfaceStyle) == NIL
            theme = light
        else
            theme = dark
        endif
    endif
else if macOS_10.14
    if UserDefaults(AppleInterfaceStyle) == NIL
        theme = light
    else
        theme = dark
    endif
endif

You can check a macOS sample app here: https://github.com/ruiaureliano/macOS-Appearance .

Cheers 💪

In macOS, the best way to find the current effective appearance (what is actually being displayed) is to look at NSApplication.effectiveAppearance . This value is observable with KVO and can be accessed through the NSApp singleton. A good article regarding watching these changes Supporting Dark Mode: Responding to Change which covers observing this particular value.

General macOS note: Reading the configuration settings from the global user preferences will get you what was last stored, but it won't get you whatever interpretation the OS currently has of that value (which, as you've shown in this example, can shift over time). This is what you're running into here. As a general rule, if you find yourself reading NSUserDefaults for keys that are not defined in the API, you should look around for another approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM