14

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)
}
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
Kosmetika
  • 20,774
  • 37
  • 108
  • 172
  • 3
    The answer you reference does not answer this question, which is asking how to pass arguments to a function. dismiss() vs dismiss(theParameter :String) for instance. – Scooter Aug 07 '14 at 15:18

2 Answers2

18

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(_:)))
Nirav D
  • 71,513
  • 12
  • 161
  • 183
dasdom
  • 13,975
  • 2
  • 47
  • 58
8

You don't pass arguments in selectors. You only represent that there is one with a colon. Additionally, you don't have to use the Selector type at all. If you pass in a String literal, it is converted to a Selector for you.

gestureRecognizer.addTarget(self, action:"dismiss:")
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281