Search code examples
swiftright-clicknsbutton

Recognize if nsbutton is pressed with a right mouse button swift


I have many NSButtons made programmatically and I need to recognize, if one of the buttons is pressed with right mouse button. Is there any way to do it in swift?

Code of creating buttons:

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
    }

Solution

  • I found the solution. You can add NSClickGestureRecognizer to each of buttons with this code:

    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
        }
    

    And in function rightClick you can access the button the following way:

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