objective-cmacos-darkmode

Updating programmatically set colors on Mode change (dark mode, light mode) on macOS (objective-c)


i am on macOS, objective-c, not iOS. XCode 12.

In a lot of views i set colors like this:

self.menuIconBar.wantsLayer = YES;
self.menuIconBar.layer.backgroundColor = [NSColor colorNamed:@"color_gradient_right"].CGColor;

Whenever the user changes the Appeareance, e.g. to Dark mode, i expect my colors to change according to the Asset setup:

enter image description here

Unfortunately, nothing happens. BUT: The same color applied in IB directly changes as expected. Still i'd need them to change programmatically too.

Then i tried to hook on notifications:

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

I receive the notifications, but when i then call the same code like above again, still the wrong color is loaded.

self.menuIconBar.layer.backgroundColor = [NSColor colorNamed:@"color_gradient_right"].CGColor;

Any help appreciated


Solution

  • As of macOS 11 one should use the performAsCurrentDrawingAppearance: instance method and add anything to apply after an appearance change into the given block.