【问题标题】:Why UIButton.addTarget needs a ":" after the string representing the action?为什么 UIButton.addTarget 在代表动作的字符串后面需要一个“:”?
【发布时间】:2015-03-06 15:02:05
【问题描述】:

我有以下代码:

button.addTarget(self, action: "buttonIsPressed:", forControlEvents: .TouchDown)

为什么我需要在操作字符串后面加上“:”?

【问题讨论】:

    标签: ios iphone cocoa-touch swift uikit


    【解决方案1】:

    它来自 Objective-C。基本上这意味着动作方法需要一个参数。在您的情况下,传递的参数将是 sender(即生成要调用的操作的 UIButton。

    【讨论】:

    • 感谢您的回答。这是为Apple开发时的某种操作系统模式吗?我能在其他情况下找到这种模式吗?
    • 这里你只是使用了常见的 oop target action 模式。 : 只是 Objective-C messaging 语法的遗留物。 UIKit 是一个纯 Objective-C 框架。你可以看一下 Objective-C 的一个非常基本的介绍(一种 hello world 教程),看看你通过了什么样的语法。
    • 感谢 Matteo,我会在互联网上寻找更多基础知识。
    【解决方案2】:

    因为您的函数 buttonIsPressed 有 1 个参数。 one : 等于一个参数

    【讨论】:

      【解决方案3】:

      你不需要它。但是你必须有不带参数的函数。

      func buttonIsPressed(){
          println("button pressed")
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多