Reputation: 108
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.
Upvotes: 1
Views: 2083
Reputation: 1562
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 💪
Upvotes: 2
Reputation: 17491
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.
Upvotes: 1