xcode 9.0.1 / swift 4, No method declared with Obj

2019-06-03 17:15发布

问题:

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?

回答1:

You should prefix the function with @objc to make it visible to the Objective-C runtime, e.g.:

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


标签: swift swift4