【问题标题】:NSButton Event Handling in Xcode 6 with Swift带有 Swift 的 Xcode 6 中的 NSButton 事件处理
【发布时间】:2014-07-29 02:55:56
【问题描述】:

我想快速设置 NSButton 的动作和目标。在以前的 Xcode 版本中,有 setAction 和 setTarget 方法,但它们不再包含在 Cocoa 库中(或者据我所知,它们不是)。 Swift 中与 for 的新库的等价物是什么:

    NSButton *myButton = [NSButton alloc];
    [myButton setTarget:self];
    [myButton setAction:@selector(myMethodToCallOnClick:)];

【问题讨论】:

    标签: macos event-handling swift nsbutton


    【解决方案1】:

    在 objC 中几乎相同,在选择器方面略有不同。现在 swift 2.2 和 lesser 在定义选择器时是有区别的。

    下面指定了“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
    

    (对不起,有趣的颜色,stackoverflow 没有得到#selector 的东西......认为它是一个评论。)

    如果您使用 swift 2.2 或更高版本编写代码,则不需要 #if #else #endif,我只是想演示一下不同之处。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      • 2017-01-02
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      相关资源
      最近更新 更多