This question already has an answer here:
- How can I deal with @objc inference deprecation with #selector() in Swift 4? 5 answers
I use swift 4
to build my UI,I create a UIButton
and want to add a target to it.
But the complier throw an warning: 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);
}
When I click the warning triangle try to fix this.
Wrap the selector name in parentheses to suppress this warning
.
It just wrap the selector name in parentheses.
button.addTarget(self, action: Selector(("onClick:forEvent:")), for: UIControlEvents.touchUpInside)
build success, but when I click the button.
throw an error
libc++abi.dylib: terminating with uncaught exception of type NSException
I know it can be changed to #selector(ViewClass.methodName)
and @objc func methodName() {..}
way.
but why Selector
not working ? Is this a correct swift 4
way?