检测 NSView 上的鼠标左键和右键单击

Detect left and right mouse click on NSView

在 Swift 中:我创建了一个简单的 NSView,现在想要执行不同的功能,具体取决于按下的是哪个鼠标按钮(向左或向右)。我该如何检测?

你陷阱相应的 mouseDown 事件

import Cocoa

class MyView : NSView {
    override func mouseDown(theEvent : NSEvent) {
        println("left mouse")
    }

    override func rightMouseDown(theEvent : NSEvent) {
        println("right mouse")
    }
}

查看NSResponder了解更多魔法。

Swift 4

import Cocoa

class MyView : NSView {
    override func mouseDown(with theEvent: NSEvent) {
        print("left mouse")
    }

    override func rightMouseDown(with theEvent: NSEvent) {
        print("right mouse")
    }
}