Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect switch between macOS default & dark mode using Swift 3

I want to change my status bar app icon when the user switches from default to dark mode and vice versa (using Swift 3). Here’s what i have so far:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    DistributedNotificationCenter.default().addObserver(self, selector: #selector(darkModeChanged(sender:)), name: "AppleInterfaceThemeChangedNotification", object: nil)
}

...

func darkModeChanged(sender: NSNotification) {
    print("mode changed")
}

Unfortunately, it’s not working. What am I doing wrong?

like image 523
ixany Avatar asked Aug 19 '16 23:08

ixany


2 Answers

I'm using this Swift 3 syntax successfully:

DistributedNotificationCenter.default.addObserver(self, selector: #selector(interfaceModeChanged(sender:)), name: NSNotification.Name(rawValue: "AppleInterfaceThemeChangedNotification"), object: nil)

func interfaceModeChanged(sender: NSNotification) {
  ...
}
like image 191
Jeffrey Morgan Avatar answered Oct 15 '22 03:10

Jeffrey Morgan


Swift 5, Xcode 10.2.1, macOS 10.14.4

Great stuff. My two cents around @Jeffrey's answer:

extension Notification.Name {
    static let AppleInterfaceThemeChangedNotification = Notification.Name("AppleInterfaceThemeChangedNotification")
}

So one could (instead of rawValue):

func listenToInterfaceChangesNotification() {
    DistributedNotificationCenter.default.addObserver(
        self,
        selector: #selector(interfaceModeChanged),
        name: .AppleInterfaceThemeChangedNotification,
        object: nil
    )
}

Remember the @objc attribute:

@objc func interfaceModeChanged() {
    // Do stuff.
}
like image 2
backslash-f Avatar answered Oct 15 '22 03:10

backslash-f