长按手势上正在执行多项操作

Art*_*der 1 ios swift uilongpressgesturerecogni

我正在尝试长按操作(目前,我只是在打印数据)。但是,每当我在模拟器/电话中做长按手势时,它都会重复几次该动作。每当长按手势被激活时,如何使其仅执行一次正确的动作?

不好意思,我对iOS开发还很陌生。

这是我的代码:

@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

}
Run Code Online (Sandbox Code Playgroud)

Sur*_*eet 5

手势识别器功能以其当前状态多次调用。如果您想在长按手势被激活时做某事

您应该对手势状态应用验证,如下所示:

       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

        }
Run Code Online (Sandbox Code Playgroud)