2016-11-22 46 views
3

外释放我有一个自定义NSView子类与(例如)以下方法:的NSView不接收mouseUp事件:事件时鼠标按钮的视图

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") } 

只要鼠标(按钮)被按下,拖动并释放视图内的所有内容,这工作正常。但是,当鼠标在视图内部被压低时,移动到视图外部,并且只有这样才能释放,我永远不会收到事件。

P.S .:呼叫super的实施没有帮助。

回答

5

Apple的鼠标事件文档中的Handling Mouse Dragging Operations部分提供了一个解决方案:显然,我们在使用鼠标跟踪循环跟踪事件时收到了mouseUp事件。

下面是从文档中示例代码的变种,适合雨燕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") } 
+0

你发现这个答案,并在一分钟内转换的代码? – Willeke

+2

我写了这个问题,但在提交之前找到了答案。由于StackOverflow在提问时明确地提供了“回答你自己的问题 - 分享你的知识,问答风格”选项,所以我利用了这一点,因为我认为还有其他人也可以从中受益。 – MrMage

+0

不要忘记接受你的答案。 – Willeke

相关问题