【问题标题】:How to detect when user changes Spaces on macOS?如何检测用户何时更改 macOS 上的空间?
【发布时间】:2019-06-03 22:01:22
【问题描述】:

我正在尝试让 macOS 应用程序检测用户何时切换空间。

虽然更新为

,但主要遵循此建议 (Detecting when a space changes in Spaces in Mac OS X)
import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(_ aNotification: Notification) {

        NotificationCenter.default.addObserver(self, selector: #selector(self.spaceChange), name: NSWorkspace.activeSpaceDidChangeNotification, object: nil)
    }

    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        return true
    }

    @objc func spaceChange() {
        print("space did change")
    }

}

这似乎很好,至少它编译时没有警告/错误。

当我切换 Spaces 时,我希望在应用程序运行时将“space did change”打印到日志中。但是,它永远不会打印到日志中。

【问题讨论】:

    标签: swift macos notificationcenter


    【解决方案1】:

    是的,这里的问题是我用错了NotificationCenter,我们需要:

    NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(self.spaceChange), name: NSWorkspace.activeSpaceDidChangeNotification, object: nil)
    

    【讨论】:

      猜你喜欢
      • 2012-01-23
      • 1970-01-01
      • 2019-06-21
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多