Multiple actions being performed on Long Press Gesture

979 views Asked by At

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

}
1

There are 1 answers

4
Surjeet Singh On BEST ANSWER

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

        }