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
  • 24,971
  • 24
  • 101
  • 136
Kosmetika
  • 20,095
  • 37
  • 101
  • 164
  • 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
  • 68,014
  • 12
  • 152
  • 178
dasdom
  • 13,829
  • 2
  • 44
  • 56
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
  • 126,953
  • 40
  • 282
  • 279