5

I am having a little trouble with NSButton's action. I programmatically create a button ...

let continueButton = NSButton(title: "Continue", target: self, action: #selector(self.continueButtonClicked))

... to call this function:

@objc func continueButtonClicked() {
    print("continueButtonClicked")
}

However, continueButtonClicked is never called and the button appears to be disabled. I've tried enabling it, but that didn't do the trick.

Am I missing something?

Jan Kaiser
  • 830
  • 1
  • 8
  • 22

2 Answers2

4

I think you need to include sender information in the method. The following code should work and is compatible with Swift 4.

let continueButton = NSButton(title: "Continue", target: self, action: #selector(self.continueButtonClicked(_:)))

@objc func continueButtonClicked(_ sender: NSButton) {
    print("Continue button clicked")
}
Chris
  • 4,009
  • 3
  • 21
  • 52
  • Thanks, this answer is great! I immediately adopted it. However, it wasn't the fix for my particular problem. – Jan Kaiser Mar 26 '18 at 10:49
  • 1
    Thanks @JanKaiser, sorry it wasn’t what you needed but I’m glad to see you found the solution! :) – Chris Mar 26 '18 at 11:13
2

Okay, it turns out, the button did call the action, but it only reacted after a few seconds of pressing on it. I managed to figure out that the reason for that was an NSClickGestureReckognizer that I had on the button's superview. Disabling it for the time the button is shown fixed the issue for me.

I hope this helps someone experiencing similar issues.

Jan Kaiser
  • 830
  • 1
  • 8
  • 22