2014-12-29 52 views
4

当用户长时间按下地图超过2-4秒时,UILongPressGestureRecognizer被触发两次。我怎样才能确保它只会被解雇一次?UILongPressGestureRecognizer被解雇两次

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) 

} 

回答

27

你必须检查手势recognizer's state的开始姿势:

func action(gestureRecognizer:UIGestureRecognizer) { 
    if gestureRecognizer.state == UIGestureRecognizerState.Began { 
     // ... 
    } 
} 
1

长按手势是连续的。当在指定的时间段(minimumPressDuration)按下允许的手指的数量(numberOfTouchesRequired)并且触摸不超过允许的移动范围(allowableMovement)时,手势开始(UIGestureRecognizerStateBegan)。手指移动时,手势识别器转换到“更改”状态,并且当任何手指抬起时手势识别器结束(UIGestureRecognizerStateEnded)。

尝试这样:

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


func someFunc(gestureRecognizer: UILongPressGestureRecognizer){ 
if gestureRecognizer.state == .began { 
//do something 
}