2

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?

Hamish
  • 78,605
  • 19
  • 187
  • 280
Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • 1
    Compare https://stackoverflow.com/q/44390378/2976878 (dupe?). You need to expose `onClick(_:forEvent:)` to Obj-C regardless of whether you use `Selector`'s initialiser or `#selector` (the latter is preferable though). Target action is an Obj-C pattern; the Obj-C runtime is needed in order to lookup the implementation to call for a given selector. – Hamish Oct 19 '17 at 13:21

1 Answers1

4

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)
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
  • Also add selector in the following form: `#selector(onClick(sender:event:))` – MrDEV Jan 21 '18 at 15:34
  • 1
    thank you very much you really save my day after 2 hours of search for nothing , thank you very much – Mosa Apr 22 '18 at 11:28
  • textField.addTarget(self, action: #selector (self.textChanged), for: .editingChanged), this worked for me – Pawan Sep 11 '18 at 13:53