I'm creating a Mac menu bar app that I'd like to be notified when the user switches the visible desktop space (including external monitors). This is a menu bar only app (i.e no actual window).
I've seen a few similar questions, but none of the answers seemed to work for me. Most answers I've seen involve observing NSWorkspaceActiveSpaceDidChangeNotification
on the NSWorkspace
's notification center.
I've tried observing this in my AppDelegate in applicationDidFinishLaunching
I have the following code:
NSWorkspace.sharedWorkspace().notificationCenter.addObserver(self,
selector: Selector(spaceChanged()),
name: NSWorkspaceActiveSpaceDidChangeNotification,
object: nil)
In my spaceChanged()
function I'm just printing something to console for debugging purposes. This function only ever gets called on app launch. Whenever I change the desktop space though I never get notified.
Is there something I'm missing? Any help is appreciated.
Rather than Selector(spaceChanged())
you should use #selector(spaceChanged)
. With Selector(spaceChanged())
, you're actually calling this function immediately, and using the result (which is probably just an empty tuple ()
) to create a null selector. The latter syntax actually creates the proper selector referencing your spaceChanged
function.
An update for Swift:
NSWorkspace.shared.notificationCenter.addObserver(
self,
selector: #selector(spaceChanged),
name: NSWorkspace.activeSpaceDidChangeNotification,
object: nil
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With