4

I have multiple NSButtons generated with this code:

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
}

And I need to add the NSClickGestureRecognizer to each of them to recognize secondary mouse button clicks. Is there any way to do that programmatically?

1 Answers1

11

This should work:

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

and later

func buttonGestured(g:NSGestureRecognizer) {
    debugPrintln(g)
    debugPrintln(g.view)
    if let v = g.view as? NSButton {
        debugPrintln("tag: \(v.tag)")
    }
}
emrys57
  • 6,679
  • 3
  • 39
  • 49
  • 1
    `g.action = Selector("buttonGestured:")` has to be written as `g.action = #selector(ViewController.buttonGestured(_:))` now – Hope May 14 '16 at 06:42