I use 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);
}
当我单击警告三角形时,请尝试解决此问题。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)
and @objc func methodName() {..}
way.
but why Selector
不工作?这是正确的吗swift 4
way?