我在代码中有两种手势,一种是通过触摸在地图上添加图钉,另一种是删除旧图钉。 问题是添加手势与滚动地图手势混淆了,当我在地图上滚动时,它使我添加了图钉而不是有时拖动
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)
}
答案 0 :(得分:0)
为避免手势识别器相互冲突,可以将它们设置为有条件地触发。例如,除非平移(拖动/滚动)手势失败,否则您可以防止长按手势触发:
首先添加用于滚动手势的手势识别器:
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”上的文档。