以编程方式swift将NSClickGestureRecognizer添加到NSButton

时间:2015-03-30 14:36:46

标签: xcode cocoa swift gesture nsbutton

我使用此代码生成了多个NSButton:

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
}

我需要为每个人添加NSClickGestureRecognizer以识别鼠标左键点击次数。有没有办法以编程方式做到这一点?

1 个答案:

答案 0 :(得分:10)

这应该有效:

let g = NSClickGestureRecognizer()
g.target = self
g.buttonMask = 0x2 // right button
g.numberOfClicksRequired = 1
g.action = Selector("buttonGestured:")
but.addGestureRecognizer(g)

以后

func buttonGestured(g:NSGestureRecognizer) {
    debugPrintln(g)
    debugPrintln(g.view)
    if let v = g.view as? NSButton {
        debugPrintln("tag: \(v.tag)")
    }
}