Search code examples
swiftuitapgesturerecognizer

Gesture recognizer issues


I'm having trouble wrapping my brain around gesture recognizers. I want to target a subview. Here's an example that works with the main view:

let gesture = UITapGestureRecognizer(target: hex_pin_view!, action: #selector(openEmojis(sender:)))
gesture.delegate = self
mapView.addGestureRecognizer(gesture)

Here's the subview target, this dose not work and is what I'm looking for:

let gesture = UITapGestureRecognizer(target: hex_pin_view!.add_emoji_img_view, action: #selector(openEmojis(sender:)))
gesture.delegate = self
mapView.addGestureRecognizer(gesture)

I'm getting a crash error:

unrecognized selector sent to instance

Tho the selector is the same, I don't get it.

Anyone have a clue what I could be doing wrong?


Solution

  • The target of a gesture recogniser is the object that will receive messages from the gesture recogniser. or simply put, the object that holds the function that will handle the message.

    Alot of the time the target: is set to self.

    selector is the function/method that will handle the messages.

    let gesture = UITapGestureRecognizer(target: self, action: #selector(openEmojis(sender:)))
    gesture.delegate = self
    mapView.addGestureRecognizer(gesture)
    

    So there, the currrent class/object should have a method called openEmojis. The gesture is added to the mapView here

    mapView.addGestureRecognizer(gesture)
    

    So when the map gets tapped, your function should be called.

    If you want the gesture to trigger when your subview is tapped. instead add the gesture recogniser to the subview instead:

    add_emoji_img_view.addGestureRecognizer(gesture)