UILongPressGestureRecognizer被触发两次

8

当用户在地图上长按2-4秒时,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)

}
2个回答

39

在开始手势时,您需要检查手势识别器的state

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

4
长按手势是连续的动作。当指定时间(minimumPressDuration)内按下了允许的手指数量(numberOfTouchesRequired),并且触摸没有移动超出允许的移动范围(allowableMovement),则手势开始(UIGestureRecognizerStateBegan)。每当有一个手指移动时,手势识别器将转换到Change状态。当任何一个手指抬起时,手势结束(UIGestureRecognizerStateEnded)。尝试像这样做:
let longGesture = UILongPressGestureRecognizer(target : self,
 action : #selector(someFunc(gestureRecognizer:)))


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接