长按手势识别器生成重复位置 (SWIFT)



我正在制作一个应用程序,您可以在其中通过长按将图钉添加到地图位置。但是,长按似乎正在复制位置。这是我的代码:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation = locations[0]
if activePlace == -1 {
latitude = userLocation.coordinate.latitude
longitude = userLocation.coordinate.longitude
} else {
latitude = Double(latitudePassed)!
longitude = Double(longitudePassed)!
}

let latDelta : CLLocationDegrees = 0.05
let lonDelta : CLLocationDegrees = 0.05
let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta)
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = MKCoordinateRegion(center: location, span: span)
map.setRegion(region, animated: true)
let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longpress(gestureRecognizer:)) )
uilpgr.minimumPressDuration = 2
map.addGestureRecognizer(uilpgr)

}
@objc func longpress(gestureRecognizer: UIGestureRecognizer) {
let touchpoint = gestureRecognizer.location(in: self.map)
print(touchpoint)
let coordinate = map.convert(touchpoint, toCoordinateFrom: self.map)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = "New Place"
let annotationLat = coordinate.latitude
let annotationLon = coordinate.longitude
places.append(["name": annotation.title!, "latitude": String(annotationLat), "longitude": String(annotationLon)])
map.addAnnotation(annotation)
}

如您所见,我在函数开始时打印接触点,并且多次打印相同的位置 - 有时两次,有时多达 12 次。我已经拖网了堆栈溢出,找不到类似的问题......任何帮助将不胜感激。

长按手势是连续的。

尝试使用.began状态,如下所示:

@objc func longpress(gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer.state == .began {
let touchpoint = gestureRecognizer.location(in: self.map)
print(touchpoint)
let coordinate = map.convert(touchpoint, toCoordinateFrom: self.map)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = "New Place"
let annotationLat = coordinate.latitude
let annotationLon = coordinate.longitude
places.append(["name": annotation.title!, "latitude": String(annotationLat), "longitude": String(annotationLon)])
map.addAnnotation(annotation)
}
}

还要尝试只触发一次addGestureRecognizer,也许在您设置/启动mapviewDidLoad中,所以这应该只是在 viewDidLoad 中,并在初始化map后触发:

let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longpress(gestureRecognizer:)) )
uilpgr.minimumPressDuration = 2
map.addGestureRecognizer(uilpgr)

要了解有关UIGestureRecognizer States的更多信息,请遵循Apple的文档:https://developer.apple.com/documentation/uikit/uigesturerecognizer/state

最新更新