首页 > 解决方案 > 长按手势识别器产生重复位置 (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 次。我已经搜索了 StackOverflow 并且找不到类似的问题......任何帮助将不胜感激。

标签: iosswiftlong-pressuilongpressgesturerecogni

解决方案


长按手势是连续的。

尝试使用.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你设置/启动的地方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


推荐阅读