Artvader
Artvader

Reputation: 958

Multiple actions being performed on Long Press Gesture

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

}

Upvotes: 1

Views: 1009

Answers (1)

Surjeet Singh
Surjeet Singh

Reputation: 11949

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

        }

Upvotes: 5

Related Questions