NSView在视图外部释放鼠标按钮时不会接收到mouseUp:事件 [英] NSView does not receive mouseUp: event when mouse button is released outside of view

查看:587
本文介绍了NSView在视图外部释放鼠标按钮时不会接收到mouseUp:事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定制的 NSView 子类与(例如)以下方法:

I have a custom NSView subclass with (for example) the following methods:

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

As只要按住鼠标(按钮),拖动并释放视图内的所有内容,这样可以正常工作。但是,当鼠标在视图中被按下时,移动到视图外面,只有释放,我从未收到 mouseUp 事件。

As long as the mouse (button) is pressed, dragged and released all inside the view, this works fine. However, when the mouse is depressed inside the view, moved outside the view, and only then released, I never receive the mouseUp event.

PS:调用超级实现无效。

P.S.: Calling the super implementations does not help.

推荐答案

处理鼠标拖动操作 Apple的鼠标事件文档部分提供了一个解决方案:显然,我们在跟踪时收​​到 mouseUp 事件

The Handling Mouse Dragging Operations section of Apple's mouse events documentation provided a solution: Apparently, we do receive the mouseUp event when tracking events with a mouse-tracking loop.

以下是适用于Swift 3的文档示例代码的变体:

Here's a variant of the sample code from the documentation, adapted for 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") }

这篇关于NSView在视图外部释放鼠标按钮时不会接收到mouseUp:事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆