识别是否用鼠标右键按下 nsbutton swift

Recognize if nsbutton is pressed with a right mouse button swift

我有许多以编程方式制作的 NSButton,如果其中一个按钮是用鼠标右键按下的,我需要识别。 swift有什么办法吗?

创建按钮的代码:

var height = 0
var width = 0

var ar : Array<NSButton> = []

var storage = NSUserDefaults.standardUserDefaults()

height = storage.integerForKey("mwHeight")
width = storage.integerForKey("mwWidth")

var x = 0
    var y = 0
    var k = 1
    for i in 1...height {
        for j in 1...width {
            var but = NSButton(frame: NSRect(x: x, y: y + 78, width: 30, height: 30))
            but.tag = k
            but.title = ""
            but.action = Selector("buttonPressed:")
            but.target = self
            but.bezelStyle = NSBezelStyle(rawValue: 6)!
            ar.append(but)
            self.view.addSubview(but)
            x += 30
            k++
        }
        y += 30
        x = 0
    }

您的 'buttonPressed' 函数将通过按下的 NSButton 被调用。

func buttonPressed(b:NSButton) {
    debugPrintln(b.tag)
}

该代码将打印出您在制作按钮时指定的按钮标签。

我找到了解决方案。您可以使用以下代码将 NSClickGestureRecognizer 添加到每个按钮:

var x = 0
    var y = 0
    k = 1
    for i in 1...height {
        for j in 1...width {
            var but = NSButton(frame: NSRect(x: x, y: y + 78, width: 30, height: 30))
            but.tag = k
            but.title = ""
            but.action = Selector("buttonPressed:")
            but.target = self
            but.bezelStyle = NSBezelStyle(rawValue: 6)!

            var ges = NSClickGestureRecognizer()
            ges.target = self
            ges.buttonMask = 0x2 //for right mouse button
            ges.numberOfClicksRequired = 1
            ges.action = Selector("rightClick:")
            but.addGestureRecognizer(ges)

            ar.append(but)
            self.view.addSubview(but)
            x += 30
            k++
        }
        y += 30
        x = 0
    }

在函数 rightClick 中,您可以通过以下方式访问按钮:

func rightClick(sender : NSGestureRecognizer) {
    if let but = sender.view as? NSButton {
        // access the button here
    }
}