【发布时间】: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 运行时才能查找实现以调用给定的选择器。