首页 > 解决方案 > 地图滚动手势和添加手势混淆

问题描述

我的代码中有两个手势,一个是通过触摸在地图上添加一个大头针,另一个是删除旧大头针。问题是添加手势与滚动地图手势混淆,当我在地图上滚动时,它会让我添加图钉而不是有时拖动

类 PlaceYourPinpointViewController: UIViewController, UIGestureRecognizerDelegate {

// MARK: - Variables

@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var nextBarButton: UIBarButtonItem!
let annotation = MKPointAnnotation()

// MARK: - IOS Basic

override func viewDidLoad() {
    super.viewDidLoad()
    addAnnotationGesture()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    setLaunchZoom()
}

// MARK: - Actions

@IBAction func cancel() {
    dismiss(animated: true, completion: nil)
}

@objc func addPin(gestureRecognizer: UIGestureRecognizer) {
    let touchPoint = gestureRecognizer.location(in: mapView)
    let newCoordinates = mapView.convert(touchPoint, toCoordinateFrom: mapView)

    annotation.coordinate = newCoordinates
    self.mapView.addAnnotation(annotation)
    nextBarButton.isEnabled = true
}

@objc func removePin(gestureRecognizer: UIGestureRecognizer) {
    self.mapView.removeAnnotation(annotation)
}

// MARK: - Private Methods

func addAnnotationGesture() {
    let addAnnotationGesture = UILongPressGestureRecognizer(target: self, action: #selector(addPin))
    addAnnotationGesture.minimumPressDuration = 0.065
    mapView.addGestureRecognizer(addAnnotationGesture)

    let removeAnnotationGesture = UITapGestureRecognizer(target: self, action: #selector(removePin))
    removeAnnotationGesture.numberOfTapsRequired = 1
    self.mapView.addGestureRecognizer(removeAnnotationGesture)

}

func setLaunchZoom() {
    let region = MKCoordinateRegion(center: mapView.userLocation.coordinate, latitudinalMeters: 600, longitudinalMeters: 600)
    mapView.setRegion(mapView.regionThatFits(region), animated: true)
}

标签: swift

解决方案


为避免手势识别器相互冲突,您可以将它们设置为有条件地触发。例如,您可以阻止长按手势触发,除非平移(拖动/滚动)手势失败:

首先为滚动手势添加一个手势识别器:

let panGesture = UIPanGestureRecognizer(target: self, action: nil)
panGesture.delegate = self
mapView.addGestureRecognizer(panGesture)

然后实现shouldBeRequiredToFailBy方法:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, 
         shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
   // Do not begin the long press unless the pan fails. 
   if gestureRecognizer == self.panGesture && 
          otherGestureRecognizer == self.addAnnotationGesture {
      return true
   }
   return false
}

另请参阅“ Preferring One Gesture Over another ”的文档。


推荐阅读