Swift: Gesture Recognizer unrecognized selector sent to instance
Asked Answered
A

2

5

I'm attempting to make a gesture recognizer in XCode, so that I can tap on my MKMapView and preform some actions. However, I am receiving the "unrecognized selector sent to instance" whenever I long-press the map.

Here is my code in viewDidLoad:

let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: "handleTap:");
self.mapViewPlace.addGestureRecognizer(gestureRecognizer);

And here is the function later on:

func handleTap(gestureReconizer: UILongPressGestureRecognizer) {

}

Any ideas?

Arlenearles answered 12/12, 2016 at 23:6 Comment(5)
Please add the full wording for the error. The error usually tells you what's wrong, that's what it's for.Palanquin
try to change action: "handleTap" to action:@selector("handleTap"Wheeler
Neo is close - it's #selector, not @selector.Tears
I would not expect the code you posted to compile in Swift 3. The new syntax for an action is action: #selector(selector_name), as described by @dfd in his answer.Earl
True. If I may add a comment, we need to distinguish better on this site between Swift 3 or not. (That. Not Swift 2.x or not.)Tears
T
7

Please, give Neo credit. You need to change your syntax to this:

let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleTap)

Side note: For Swift you do not need semi-colons the end your code lines.

Tears answered 12/12, 2016 at 23:24 Comment(2)
This solved the issue, thanks! For some reason, I couldn't find any guides on how to do this in the most recent version of Swift. Thank you to Neo for your help as well.Arlenearles
This still works with swift 4 thank you for the answer and the right syntax!Coupling
M
0

By default Swift generates code that is only available to other Swift code, but if you need to interact with the Objective-C runtime – all of UIKit, for example – you need to tell Swift what to do.

So just add it and modify selector declaration:

@objc func handleTap(gestureReconizer: UILongPressGestureRecognizer) {
...
}
...
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(handleTap(gestureReconizer:)))
Melt answered 14/8, 2020 at 1:11 Comment(1)
More info hackingwithswift.com/example-code/language/…Melt

© 2022 - 2024 — McMap. All rights reserved.