How can dark mode be detected on macOS 10.14?

前端 未结 6 1326
天涯浪人
天涯浪人 2020-12-13 20:51

In macOS 10.14 users can choose to adopt a system-wide light or dark appearance and I need to adjust some colours manually depend of the current mode.

6条回答
  •  天命终不由人
    2020-12-13 21:41

    For me neither of these answers worked, if I wanted a global state, not per view, and I didn't have access to the view, and I wanted to be notified for updates.

    The solution was to ask for NSApp.effectiveAppearance in the main thread, or at least after the current callback method has returned to the system.

    So, first I have to register, following the directions of Saúl Moreno Abril, with a code like

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

    then on the callback method write something like

    -(void)themeChanged:(NSNotification *) notification {
        [self performSelectorOnMainThread:@selector(themeChangedOnMainThread) withObject:nil waitUntilDone:false];
    }
    

    and then the actual code:

    - (void) themeChangedOnMainThread {
        NSAppearance* appearance = NSApp.effectiveAppearance;
        NSString* name = appearance.name;
        BOOL dark = [appearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]] == NSAppearanceNameDarkAqua;
    }
    

    Also the answer from Borzh helped, but is seemed more fragile than the others.

提交回复
热议问题