1

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

抱歉,我对 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

}
4

1 回答 1

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

        }
于 2017-09-16T16:16:25.700 回答