斯威夫特新手。
我在执行一项琐碎的任务时遇到了麻烦。我要做的就是 按需 获取鼠标光标的x,y坐标。我宁可 不要 等到鼠标移动事件触发后再抓住指针的坐标。
将不胜感激!
您应该看看NSEvent方法mouseLocation
编辑/更新: Xcode 11•Swift 5.1
如果您希望在应用程序处于活动状态时监视任何窗口上的事件,则可以添加与mouseMoved掩码匹配的LocalMonitorForEvents,如果未处于活动状态,则可以添加GlobalMonitorForEvents。请注意,您需要将window属性设置acceptsMouseMovedEvents为true
acceptsMouseMovedEvents
true
import Cocoa class ViewController: NSViewController { lazy var window: NSWindow = self.view.window! var mouseLocation: NSPoint { NSEvent.mouseLocation } var location: NSPoint { window.mouseLocationOutsideOfEventStream } override func viewDidLoad() { super.viewDidLoad() NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved]) { print("mouseLocation:", String(format: "%.1f, %.1f", self.mouseLocation.x, self.mouseLocation.y)) print("windowLocation:", String(format: "%.1f, %.1f", self.location.x, self.location.y)) return $0 } NSEvent.addGlobalMonitorForEvents(matching: [.mouseMoved]) { _ in print(String(format: "%.0f, %.0f", self.mouseLocation.x, self.mouseLocation.y)) } } override func viewWillAppear() { super.viewWillAppear() window.acceptsMouseMovedEvents = true } }
样例项目