2016-11-22 45 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

相關問題