【问题标题】:Adding an @objc method as an action to a button and getting "Argument of '#selector' does not refer to an '@objc' method, property, or initializer"将@objc 方法作为操作添加到按钮并获得“'#selector' 的参数不引用'@objc' 方法、属性或初始化程序”
【发布时间】:2019-10-20 21:28:42
【问题描述】:

我正在向我的按钮添加一个动作

let button = UIButton()
button.addTarget(self, action: #selector(touchButton(button)), for: .touchUpInside)

我有我的@objc 方法

@objc public func touchButton(_ sender: UIButton) {
    let soundNumber = soundButtons.index(of: sender)!   //The index of the button
    ...
}

为什么我仍然收到

Argument of '#selector' does not refer to an '@objc' method, property, or initializer

【问题讨论】:

  • #selector(touchButton)#selector(touchButton(_:))

标签: ios swift uibutton selector


【解决方案1】:

您使用的签名与您的 objc 方法不匹配。正确的选择器是touchButton(_:),而不是touchButton(button)

【讨论】:

  • (_:) 部分是可选的。
  • 我想要一个参数,我更新了我的代码,所以你可以看到我用那个参数做的事情
  • 什么是_:,它有什么作用
  • (_:) 指定了一个带有单个未命名参数的方法。
  • 如果命名函数有多个参数怎么办?如何在#selector 中编写它们?
猜你喜欢
  • 2017-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多