1

I'm trying to do an action during a long press (for now, I'm just printing out the data). But whenever I do the longpress gesture in the simulator/phone, it repeats the action several times. How do I make it perform the action only exactly one time whenever the long press gesture gets activated?

Apologies, I'm pretty new to iOS development.

Here's my code:

@IBAction func addRegion(_ sender: Any) {
    guard let longPress = sender as? UILongPressGestureRecognizer else
    { return }
    let touchLocation = longPress.location(in: mapView)
    let coordinate = mapView.convert(touchLocation, toCoordinateFrom: mapView)
    let region = CLCircularRegion(center: coordinate, radius: 50, identifier: "geofence")
    mapView.removeOverlays(mapView.overlays)
    locationManager.startMonitoring(for: region)
    let circle = MKCircle(center: coordinate, radius: region.radius)
    mapView.add(circle)
    print(coordinate.latitude)
    print(coordinate.longitude)

    //returns:
    // 27.4146234860156
    // 123.172249486142
    // ... (a lot of these)
    // 27.4146234860156
    // 123.172249486142

}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Artvader
  • 906
  • 2
  • 15
  • 31

1 Answers1

5

Gesture recognizer functions called multiple times with its current state. If you want to do something when long press gesture gets activated

You should apply validation for gesture state like below:

       guard let longPress = sender as? UILongPressGestureRecognizer else
        { return }

        if longPress.state == .began { // When gesture activated

        }
        else if longPress.state == .changed { // Calls multiple times with updated gesture value 

        }
        else if longPress.state == .ended { // When gesture end

        }
Surjeet Singh
  • 11,691
  • 2
  • 37
  • 54
  • And check for the `.changed` state if needed. – rmaddy Sep 16 '17 at 16:17
  • can you combine this with UIContextMenuInteraction? – uuuuuu Mar 26 '21 at 22:44
  • @uuuuuu UIContextMenuInteraction has its own gesture, and not need to add additional gestures. You can implement basic UIContextMenuInteraction with this tutorial link https://kylebashour.com/posts/ios-13-context-menus. – Surjeet Singh Mar 28 '21 at 07:22
  • @Surjeet thanks. My issue is I need to make a database call to check the status of a user before I implement gesture(gesture is image vc that returns based in db call). Is it possible to use .begin, .changed to first check db and then return the vc? – uuuuuu Mar 28 '21 at 08:27