Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observing .effectiveAppearance change from appDelegate

Tags:

xcode

macos

swift

In my appDelegate's applicationDidFinishLaunching method, I would like to observe the appearance change from light / dark mode.

Neither of these seems to do the trick:

NSApp.observe(\.effectiveAppearance) { _, _ in
    print("it works!")
}

NSApplication.shared.observe(\.effectiveAppearance) { _, _ in
    print("it works!")
}

How would I detect this change?


1 Answers

You just need to keep this observer alive by assigning it to a class level object as below,

class AppDelegate: NSObject, NSApplicationDelegate {


    private var observer: Any!

    func applicationDidFinishLaunching(_ aNotification: Notification) {

        self.observer = NSApp.observe(\.effectiveAppearance) { _, _ in
            print("it works!")
        }
    }
}
like image 50
Kamran Avatar answered Jul 14 '26 05:07

Kamran