Swift: detect space (virtual desktop) changes

May 4, 2024

In a macOS app, you can get an event when the active space changes. This happens e.g. if you have multiple virtual desktops, or full screen windows, and you swap between “spaces”, using the 3 fingers swipe on the trackpad, or the Ctrl + Left and Right shortcuts.

class MyObserver {
  init() {
    NSWorkspace.shared.notificationCenter.addObserver(
      forName: NSWorkspace.activeSpaceDidChangeNotification,
      object: nil,
      queue: nil,
      using: self.spaceDidChange
    )
  }

  func spaceDidChange(_ notification: Notification) {
    print("Desktop (space) changed")
  }
}

Looks like there’s an alternative way to call it:


class MyObserver {
  init() {
    NSWorkspace.shared.notificationCenter.addObserver(
      self,
      selector: #selector(self.spaceDidChange),
      name: NSWorkspace.activeSpaceDidChangeNotification,
      object: nil
    )
  }

  func spaceDidChange(_ notification: Notification) {
    print("Desktop (space) changed")
  }
}

Whatever works for you!

Want to leave a comment?

Join the discussion on Twitter or send me an email! 💌
This post helped you? Buy me a coffee! 🍻