Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSButton Event Handling in Xcode 6 with Swift

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:)];
like image 656
Kyle Somers Avatar asked Jul 29 '14 02:07

Kyle Somers


1 Answers

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.

like image 176
Ethan Avatar answered Oct 19 '22 19:10

Ethan