我是Swift的新手。
我遇到了一个看起来很简单的任务却遇到了麻烦。我只想在需要时获取鼠标光标的x,y坐标。我更希望在抓取指针坐标之前不必等待鼠标移动事件的触发。
感谢任何帮助!
你应该查看NSEvent的方法mouseLocation
编辑/更新: Xcode 11 • Swift 5.1
如果你想要在你的应用程序处于活动状态时监视任何窗口上的事件,你可以添加一个匹配mouseMoved掩码的LocalMonitorForEvents,如果它不是活动的,则添加一个GlobalMonitorForEvents。请注意,你需要将你的窗口属性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
}
}
您可以通过以下方法获取当前鼠标位置:
Declare this in your view controller class:
var mouseLocation: NSPoint? { self.view.window?.mouseLocationOutsideOfEventStream }
Then, you can get the current mouse location and convert in your desired view coordinates:
if let currentMouseLocation = self.mouseLocation{
let pointInTargetView = self.**targetView**.convert(currentMouseLocation, from: self.view)
}
NSEvent.mouseLocation
返回一个 NSPoint
,它表示光标在屏幕上的位置。
这在被接受的答案中提到,但没有明确说明。
mouseLocation
。我想实现一种颜色选择器,并希望在光标旁边绘制自定义视图。如果您能指导我正确的方向,那就太好了! - ixanyNSEvent.addLocalMonitorForEvents(matching: .mouseMoved) { print(NSEvent.mouseLocation()) return $0 }
来监控鼠标移动事件。如果你想在应用程序不活动时进行监控,只需将 local 替换为 global 即可。 - Leo Dabus