2017-09-16 1 views
1

長いプレス中にアクションを実行しようとしています(今のところデータを印刷しています)。しかし、私がシミュレーター/電話機でロングプレスのジェスチャーを行うたびに、それは何度かアクションを繰り返す。長いプレスのジェスチャーがアクティブになるたびに、ちょうど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 

} 

答えて

3

ジェスチャー認識機能:

は、ここに私のコードです。 長押しジェスチャーが

をアクティブ化されたときに、あなたが何かをしたい場合は、以下のようなジェスチャー状態の検証を適用する必要があります。

 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 

     } 
+0

をし、必要に応じて '.changed'状態を確認してください。 – rmaddy

関連する問題