【问题标题】:xcode 9.0.1 / swift 4, No method declared with Objective-C selector 'onClick:forEvent:' [duplicate]xcode 9.0.1 / swift 4,没有使用Objective-C选择器'onClick:forEvent:'声明的方法[重复]
【发布时间】:2017-10-19 11:39:38
【问题描述】:

我使用swift 4 来构建我的用户界面,我创建了一个UIButton 并想给它添加一个目标。

但是编译器发出警告:No method declared with Objective-C selector 'onClick:forEvent:'

button.addTarget(self, action: Selector("onClick:forEvent:"), for: UIControlEvents.touchUpInside) 
//...

func onClick(_ sender: Any, forEvent event: UIEvent) {
  print("button click", sender, event);
}

当我单击警告三角形时,请尝试解决此问题。 Wrap the selector name in parentheses to suppress this warning.

它只是将选择器名称包裹在括号中。

button.addTarget(self, action: Selector(("onClick:forEvent:")), for: UIControlEvents.touchUpInside)

构建成功,但是当我单击按钮时。

报错

libc++abi.dylib: terminating with uncaught exception of type NSException

我知道可以改成#selector(ViewClass.methodName)@objc func methodName() {..}的方式。

但是为什么Selector 不起作用?这是正确的swift 4 方式吗?

【问题讨论】:

  • 比较stackoverflow.com/q/44390378/2976878(骗人?)。无论您使用Selector 的初始化程序还是#selector(后者更可取),您都需要将onClick(_:forEvent:) 暴露给Obj-C。目标动作是一种 Obj-C 模式;需要 Obj-C 运行时才能查找实现以调用给定的选择器。

标签: swift swift4


【解决方案1】:

您应该在函数前面加上 @objc 以使其对 Objective-C 运行时可见,例如:

@objc func onClick(_ sender: Any, forEvent event: UIEvent)

【讨论】:

  • 还添加如下形式的选择器:#selector(onClick(sender:event:))
  • 非常感谢您在 2 小时的无所事事后真正拯救了我的一天,非常感谢您
  • textField.addTarget(self, action: #selector (self.textChanged), for: .editingChanged),这对我有用
猜你喜欢
  • 2016-07-09
  • 1970-01-01
  • 2012-10-15
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
  • 1970-01-01
  • 2015-06-10
相关资源
最近更新 更多