Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
}
like image 704
Kosmetika Avatar asked Jun 28 '14 13:06

Kosmetika


People also ask

How do you call a selector in Swift?

The solution to your problem is to pass the object that should run the selector method along with the selector to the initialisation of the ValueAnimator object. Also update the timerCallback() : @objc func timerCallback() { ... _ = target.

What is selector() in Swift?

Use Selectors to Arrange Calls to Objective-C Methods In Objective-C, a selector is a type that refers to the name of an Objective-C method. In Swift, Objective-C selectors are represented by the Selector structure, and you create them using the #selector expression.


1 Answers

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(_:)))
like image 194
dasdom Avatar answered Oct 23 '22 14:10

dasdom