1

我的应用程序在 Mac Os Mojave 中存在一些 UI 问题。当我切换到深色模式时,一些标签和按钮的文本内容不可见。所以我使用以下代码做了一项工作。

var interfaceStyle = NSUserDefaults.StandardUserDefaults.StringForKey("AppleInterfaceStyle");
if (interfaceStyle == "Dark") {
label.textcolor = NSColor.White;
} 

这解决了问题,但是如果我在应用程序之间切换回浅色模式正在使用标签颜色不会改变。我需要重新启动应用程序以读取代码并以默认颜色显示标签。

任何人都可以遇到这个问题吗?当用户更改 Mac Os Mojave 的外观模式(深色和浅色)时,是否有任何委托方法?

4

1 回答 1

3

You can use KVO to track theme changes (AppleInterfaceThemeChangedNotification).

A few class level "constants":

readonly NSString themeKeyString = new NSString("AppleInterfaceThemeChangedNotification");
readonly NSString dark = new NSString("Dark");
readonly Selector modeSelector = new Selector("themeChanged:");

Export method for the ObjC selector to call:

[Export("themeChanged:")]
public void ThemeChanged(NSObject change)
{
    var interfaceStyle = NSUserDefaults.StandardUserDefaults.StringForKey("AppleInterfaceStyle");
    if (interfaceStyle == "Dark")
    {
        Console.WriteLine("Now Dark");
    }
        else
    {
        Console.WriteLine("Now not Dark");
    }
}

Add observer request to notification center:

NSDistributedNotificationCenter.GetDefaultCenter().AddObserver(this, modeSelector, themeKeyString, null);

Note: I typically register this in AppDelegate.DidFinishLaunching

Remove the observer if you no longer need it:

NSDistributedNotificationCenter.GetDefaultCenter().RemoveObserver(this, themeKeyString);

BTW: The NSDistributedNotificationCenter.DefaultCenter.AddObserver helpers/overloads do not work properly in this instance...

于 2018-11-18T06:16:03.333 回答