Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILongPressGestureRecognizer getting fired twice

UILongPressGestureRecognizer is getting fired twice when user long presses on a map for over 2-4 seconds. How can I ensure it will only be fired once?

func action(gestureRecognizer:UIGestureRecognizer) {

    println("long pressed on map")


override func viewDidLoad() {
    super.viewDidLoad()

    manager = CLLocationManager()
    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest

    if activePlace == -1 {

        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()



    } else {

        var uilpgr = UILongPressGestureRecognizer(target: self, action: "action:")
        uilpgr.minimumPressDuration = 2.0
        myMap.addGestureRecognizer(uilpgr)

    }        
}

func action(gestureRecognizer:UIGestureRecognizer) {

    println("long pressed on map")
    var touchPoint = gestureRecognizer.locationInView(self.myMap)
    var newCoordinate = myMap.convertPoint(touchPoint, toCoordinateFromView: self.myMap)

    var annotation = MKPointAnnotation()
    annotation.coordinate = newCoordinate
    //annotation.title = "New Place"
    myMap.addAnnotation(annotation)

    var loc = CLLocation(latitude: newCoordinate.latitude, longitude: newCoordinate.longitude)

}
like image 239
user1406716 Avatar asked Dec 29 '14 08:12

user1406716


2 Answers

You have to check the gesture recognizer´s state for the begin of the gesture:

func action(gestureRecognizer:UIGestureRecognizer) {
    if gestureRecognizer.state == UIGestureRecognizerState.Began {
        // ...
    }
}
like image 162
zisoft Avatar answered Oct 22 '22 07:10

zisoft


Long-press gestures are continuous. The gesture begins (UIGestureRecognizerStateBegan) when the number of allowable fingers (numberOfTouchesRequired) have been pressed for the specified period (minimumPressDuration) and the touches do not move beyond the allowable range of movement (allowableMovement). The gesture recognizer transitions to the Change state whenever a finger moves, and it ends (UIGestureRecognizerStateEnded) when any of the fingers are lifted.

try something like this:

let longGesture = UILongPressGestureRecognizer(target : self,
 action : #selector(someFunc(gestureRecognizer:)))


func someFunc(gestureRecognizer: UILongPressGestureRecognizer){
if gestureRecognizer.state == .began {
//do something
}
like image 29
Sanket Ray Avatar answered Oct 22 '22 06:10

Sanket Ray