2017-09-16 42 views
1

我試圖在長按(現在,我只是打印出數據)時執行一個操作。但是,無論何時我在模擬器/手機中進行longpress手勢,它都會多次重複該操作。只要長按手勢被激活,我如何才能使其僅執行一次操作?在長按手勢上執行的多個操作

道歉,我很新的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