我有一个(例如)以下方法的自定义NSView
子类:
override func mouseDown(with event: NSEvent) { Swift.print("mouseDown") }
override func mouseDragged(with event: NSEvent) { Swift.print("mouseDragged") }
override func mouseUp(with event: NSEvent) { Swift.print("mouseUp") }
只要在 View 内全部按下,拖动并释放鼠标(按钮),就可以正常工作。但是,当在 View 内按下鼠标,在 View 外移动鼠标并释放鼠标时,我再也没有收到
mouseUp
事件。附注:调用
super
实现没有帮助。 最佳答案
Apple的鼠标事件文档的Handling Mouse Dragging Operations部分提供了一种解决方案:显然,当使用鼠标跟踪循环跟踪事件时,确实会收到mouseUp
事件。
这是文档中示例代码的一种变体,适用于Swift 3:
override func mouseDown(with event: NSEvent) {
var keepOn = true
mouseDownImpl(with: event)
// We need to use a mouse-tracking loop as otherwise mouseUp events are not delivered when the mouse button is
// released outside the view.
while true {
guard let nextEvent = self.window?.nextEvent(matching: [.leftMouseUp, .leftMouseDragged]) else { continue }
let mouseLocation = self.convert(nextEvent.locationInWindow, from: nil)
let isInside = self.bounds.contains(mouseLocation)
switch nextEvent.type {
case .leftMouseDragged:
if isInside {
mouseDraggedImpl(with: nextEvent)
}
case .leftMouseUp:
mouseUpImpl(with: nextEvent)
return
default: break
}
}
}
func mouseDownImpl(with event: NSEvent) { Swift.print("mouseDown") }
func mouseDraggedImpl(with event: NSEvent) { Swift.print("mouseDragged") }
func mouseUpImpl(with event: NSEvent) { Swift.print("mouseUp") }
关于cocoa - NSView未收到mouseUp : event when mouse button is released outside of view,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40744161/