swift - 地图滚动手势和添加手势混淆
问题描述
我的代码中有两个手势,一个是通过触摸在地图上添加一个大头针,另一个是删除旧大头针。问题是添加手势与滚动地图手势混淆,当我在地图上滚动时,它会让我添加图钉而不是有时拖动
类 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)
}
解决方案
为避免手势识别器相互冲突,您可以将它们设置为有条件地触发。例如,您可以阻止长按手势触发,除非平移(拖动/滚动)手势失败:
首先为滚动手势添加一个手势识别器:
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 ”的文档。
推荐阅读
- javascript - Electron Renderer 仅在 DevTools 打开时处理 OOM
- r - 在R中,根据另一个变量的段分配数字变量?
- python - 如何先从一个函数线程化,然后再从另一个函数线程化?
- qt - 如何让 QFileSelector 根据设备选择文件
- jsp - 为什么我的 requestDispatcher.forward(/index.jsp) 不转发并且我没有收到错误?
- javascript - 使用 fetch 删除请求后出现 404(未找到)
- r - 绘制具有两个变量的回归
- python - 列表索引超出范围,看不到哪里?
- javascript - Plotly 3D 散点图在 Vue 中不起作用
- java - 从对象 val 等于 x 的自定义对象列表中收集自定义对象