Swift - How to call Selector() on method with arguments?

Kosmetika picture Kosmetika · Jun 28, 2014 · Viewed 24.1k times · Source

I'm learning Swift and need to call my method on tap, here is the code:

var gestureRecognizer = UITapGestureRecognizer()
myView.addGestureRecognizer(gestureRecognizer)
gestureRecognizer.addTarget(self, action: Selector(dismiss(nil)))

This returns error - Could not find an overload for init that accepts the supplied arguments

I also tried like Selector("dismiss:nil") and Selector("dismiss(nil)") with no luck..

Here the method I'm calling:

func dismiss(completion: (() -> Void)!) {
    self.dismissViewControllerAnimated(true, completion: completion)
}

Answer

dasdom picture dasdom · Jun 28, 2014

Just use the name of the method as a string:

gestureRecognizer.addTarget(self, action: "dismiss:")

Edit: In Swift 3.0 you will have to use the following syntax:

gestureRecognizer.addTarget(self, action: #selector(dismiss(_:)))