gpt4 book ai didi

swift - map 滚动手势和添加手势混淆

转载 作者:行者123 更新时间:2023-11-30 11:19:49 24 4
gpt4 key购买 nike

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

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 ”的文档。

关于swift - map 滚动手势和添加手势混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51406247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com