【发布时间】:2020-05-12 18:08:23
【问题描述】:
我想在按钮单击(鼠标向上)期间接收有关鼠标移动事件的信息
我正在添加 NSTrackingArea 以查看我想要跟踪鼠标移动和鼠标拖动事件,但我仍然没有收到这些事件。
我假设NSButton 中的mouseDown 阻止了鼠标事件,所以我想出的唯一解决方案是覆盖NSButton 的mouseDown 函数而不是调用super.mouseDown,但是我需要处理按钮手动选择,我不确定这是否是正确的方法。
这是解决我的问题的正确方法吗?会不会有问题?有没有更好的解决方案?
这是测试代码,只需将按钮添加到新项目并为其分配TestButton 类。
class TestButton: NSButton {
override func mouseDown(with event: NSEvent) {
print("Mouse up")
super.mouseDown(with: event) // After removing events works.
print("Mouse down")
}
}
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let trackingArea = NSTrackingArea(rect: view.bounds, options: [.activeAlways, .mouseMoved, .enabledDuringMouseDrag], owner: self, userInfo: nil)
view.addTrackingArea(trackingArea)
}
override func mouseMoved(with event: NSEvent) {
print("Mouse moved")
super.mouseMoved(with: event)
}
override func mouseDragged(with event: NSEvent) {
print("Mouse dragged")
super.mouseDragged(with: event)
}
}
【问题讨论】:
-
view.window属性在viewDidLoad方法中将始终为nil,因此使用可选投标将acceptsMouseMovedEvents设置为true将静默失败。您需要在viewWillAppear或viewDidAppear方法中设置此属性,其中view.window不是nil -
感谢您的关注,我删除了这一行,因为它没有任何改变