Macos 如何在Catalina中检测OSX是在黑暗模式下还是在自动显示模式下
我的Mac应用程序需要根据明暗模式改变行为 在macOS Catalina中将“外观”选项选为“自动”时,检测样式的最佳方法是什么Macos 如何在Catalina中检测OSX是在黑暗模式下还是在自动显示模式下,macos,cocoa,macos-catalina,Macos,Cocoa,Macos Catalina,我的Mac应用程序需要根据明暗模式改变行为 在macOS Catalina中将“外观”选项选为“自动”时,检测样式的最佳方法是什么 NSDictionary *dict = [[NSUserDefaults standardUserDefaults] persistentDomainForName:NSGlobalDomain]; id style = [dict objectForKey:@"AppleInterfaceStyle"]; BOOL darkModeOn = ( style &
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] persistentDomainForName:NSGlobalDomain];
id style = [dict objectForKey:@"AppleInterfaceStyle"];
BOOL darkModeOn = ( style && [style isKindOfClass:[NSString class]] && NSOrderedSame == [style caseInsensitiveCompare:@"dark"] );
即使在从暗模式切换到自动外观选项后,暗模式仍为是/暗模式。在macOS中,查找当前有效外观(实际显示的内容)的最佳方法是查看。该值可通过KVO观察,并可通过
NSApp
singleton访问。这是一篇关于观察这些变化的好文章,其中包括观察这个特定值
一般macOS注意:从全局用户首选项中读取配置设置将获得上次存储的内容,但不会获得操作系统当前对该值的任何解释(如本例所示,该值可能随时间而变化)。这就是你在这里遇到的。作为一般规则,如果您发现自己正在阅读API中未定义的键的
NSUserDefaults
,您应该四处寻找另一种方法。您需要将AppleInterfaceStyle
与macOS CatalinaAppleInterfaceStyleSwitches中引入的这个新值自动组合起来
下面是一些伪代码,解释如何:
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
您可以在此处查看macOS示例应用程序:
干杯