简体   繁体   English

使用Swift进行Xcode 6中的NSButton事件处理

[英]NSButton Event Handling in Xcode 6 with Swift

I want to set the action and target for an NSButton in swift. 我想快速设置NSButton的操作和目标。 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). 在以前版本的Xcode中,有setAction和setTarget方法,但是这些方法不再包含在Cocoa库中(或者,据我所知,它们还不包括在内)。 What is the equivalent in Swift with the new library for for: 在Swift中,新库的等效项是:

    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. 它与objC几乎相同,选择器之间略有不同。 Nowadays there is a difference between swift 2.2 and lesser when defining selectors. 如今,在定义选择器时,swift 2.2和以下版本之间存在差异。

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) 波纹管在'self'上指定了回调,该回调被假定为@objc可访问的NSObject(myAction函数可能必须标记为@objc,因为选择器截至目前仍在使用objC运行时)

    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.) (对不起有趣的颜色,stackoverflow没得到#selector的东西。。。以为是评论。)

If you are writing in swift 2.2 or greater, no need for the #if #else #endif, I just wanted to demonstrate the difference. 如果您使用2.2或更高版本进行编写,则不需要#if #else #endif,我只是想证明两者之间的区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM