在Long Press Gesture上执行多项操作

时间:2017-09-16 16:10:48

标签: 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

}

1 个答案:

答案 0 :(得分:4)

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

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

       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

        }