Longpress gestureRecognizer 产生重复位置 (SWIFT)

Longpress gestureRecognizer producing duplicate locations (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 次。我搜索了 Whosebug,但找不到类似的问题...任何帮助将不胜感激。

Long-press gestures是连续的。

尝试 .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,也许在 viewDidLoad 你 setup/initiate map 的地方,所以这应该只是在 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