<分区>
我使用 swift 4
构建我的 UI,我创建了一个 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);
}
当我点击警告三角形时尝试修复此问题。
将选择器名称括在括号中以抑制此警告
。
它只是将选择器名称括在括号中。
button.addTarget(self, action: Selector(("onClick:forEvent:")), for: UIControlEvents.touchUpInside)
构建成功,但是当我点击按钮时。
抛出一个错误
libc++abi.dylib:以 NSException 类型的未捕获异常终止
我知道它可以更改为 #selector(ViewClass.methodName)
和 @objc func methodName() {..}
方式。
但为什么 Selector
不起作用?这是正确的 swift 4
方式吗?