Trying to adapt Menu Icon to Mojave dark mode

2019-07-27 23:54发布

问题:

After switching to mojave I´m trying to adapt the menu icon when the mode has changed. My app: "Application is agent (UIElement)" doesn´t have windows initially.

At the moment I´m using the NSMenuDelegate function menuWillOpen which works so far but the user has to open the menu to get the icon changed.

I wonder if there is a way to detect that the appearance has changed whithout opening the menu. I already tried applicationDidChangeScreenParameters from NSApplicationDelegate without success.

//this comes from NSMenuDelegate

- (void)menuWillOpen:(NSMenu *)menu { 
    [self adaptToDarkMode];
}

// this handles the menu icon change

 - (void) adaptMenuIcon {
    BOOL  darkModeFlag  = [self psGetDarkMode];
    NSString *iconName  = @"MenuIconBlack";

    if(darkModeFlag) {
        iconName  = @"MenuIconWhite";
    }

    NSString *filePath  = [self psBundlePathToFolder:@""];
    NSString *finalPath = [NSString stringWithFormat:@"%@%@.png", filePath, iconName];

    NSImage  *image     = [[NSImage alloc] initWithContentsOfFile:finalPath];
    pathToMenuIcons     = [self psBundlePathToFolder:@"MenuIcons"];

    [statusItem setMenu:statusMenu];
    [statusItem setTitle:@"➜"];
    [statusItem setImage: image];
    [statusItem setHighlightMode:YES];
}

回答1:

You can read global preferences:

NSString *appearance = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];

This will return Dark in dark mode.

You can also use NSDistributedNotificationCenter

[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppearanceChanged:) name:@"AppleInterfaceThemeChangedNotification" object:nil]

-(void)onAppearanceChanged:(NSNotification *)notificaton
{
 // read appearance
}