2016-11-22 5 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") } 

をビュー内でドラッグして解放しても、これはうまく動作します。しかし、マウスがビュー内で押され、ビューの外に移動してから解放されると、私はmouseUpイベントを受け取ることはありません。

P.:superの実装を呼び出すことは役に立ちません。

答えて

5

アップルのマウスイベントドキュメントの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

あなたはこの答えを見つけ、1分間にコードを翻訳しましたか? – Willeke

+2

私は質問を書いたが、提出する前に答えを見つけた。 StackOverflowは明示的に質問をするときに「あなた自身の質問に答える - あなたの知識、Q&Aスタイルを共有する」オプションを持っているので、これを利用できる他の人がいると思うので、私はこれを利用しました。 – MrMage

+0

あなたの答えを受け入れることを忘れないでください。 – Willeke

関連する問題