creating simple action if NSButton is pressed in swift
The problem lies in the way you add your selector
myButton.action = Selector(printSomething())
The syntax for adding selectors is a bit quirky, you give it a string with the name of the function, so in your case you should write:
myButton.action = Selector("printSomething")
Which should reward you with Hello
in your console.
And probably because the syntax is causing people problems it was changed in Swift 2.2, so now you write:
myButton.action = #selector(ViewController.printSomething)
instead. This means that the compiler can help you catch these errors early, which is a great step forward I think. You can read more about it in the release notes for Swift 2.2 here
So...here is your entire example:
import Cocoaclass ViewController: NSViewController { @objc func printSomething() { print("Hello") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let myButtonRect = CGRect(x: 10, y: 10, width: 100, height: 10) let myButton = NSButton(frame: myButtonRect) view.addSubview(myButton) myButton.target = self myButton.action = #selector(ViewController.printSomething) } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } }}
Hope that helps you.