2014-12-29 54 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 
}