I want to set the action and target for an NSButton in swift. In previous versions of Xcode, there were setAction and setTarget methods, but those aren't included in the Cocoa library anymore (or they aren't as far as I can tell). What is the equivalent in Swift with the new library for for:
NSButton *myButton = [NSButton alloc];
[myButton setTarget:self];
[myButton setAction:@selector(myMethodToCallOnClick:)];
It's pretty much the same it is in objC, with a slight difference around selectors. Nowadays there is a difference between swift 2.2 and lesser when defining selectors.
The bellow specifies callback on 'self' which is assumed to be a NSObject of @objc accessible (the myAction function may have to be marked as @objc because selectors still use objC runtime as of right now)
let button = NSButton()
button.target = self
#if swift (>=2.2)
button.action = #selector(myAction) // now it autocompletes!
#else
button.action = "myAction:" //old way to do it in swift
#endif
(sorry about the funny coloring, stackoverflow doesn't get the #selector stuff... thinks its a comment.)
If you are writing in swift 2.2 or greater, no need for the #if #else #endif, I just wanted to demonstrate the difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With