NSView不会接收鼠标:事件在视图外发布鼠标按钮时



我有一个自定义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") }

只要按下鼠标(按钮),拖动并全部释放在视图内,这可以正常工作。但是,当鼠标在视图内凹陷时,移动到视图外,然后才发布,我从未收到mouseUp事件。

P.S。:致电super实现无济于事。

Apple的鼠标事件文档的处理鼠标拖动操作部分提供了一个解决方案:显然,当使用鼠标跟踪循环跟踪事件时,我们确实会接收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") }

正在将其发布为我需要知道用户停止使用滑块的类似问题的答案。我需要从NSSlider或实际NSView捕获MouseUP事件。对我来说解决的解决方案是简单地捕获Mousedown事件并在退出时添加一些代码并完成我需要的工作。希望这对需要做类似事情的其他人有用。使用Xcode 11.3.1 swift 5

编写的代码
import Cocoa
class SMSlider: NSSlider {
    var calledOnExit:(()->())?
    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
    }
    override func mouseDown(with event: NSEvent) {
        super.mouseDown(with: event)
        if self.calledOnExit != nil {
            self.calledOnExit!()
        }
    }    
}
// In my main swift app
func sliderStopped() {
    print("Slider stopped moving")
}
//...
if slider == nil {
    slider = SMSlider()
}
slider?.isContinuous = true
slider?.target = self
slider?.calledOnExit = sliderStopped
//...

相关内容

  • 没有找到相关文章

最新更新