Repeating pin annotation on map

戏子无情 提交于 2019-11-29 12:09:59

Xcode 8.2 • Swift 3.0.2

You just need to check the gesture recognizer state and make sure if not .Began return. Just add this if condition at the top of your action method:

func action(_ gestureRecognizer: UIGestureRecognizer) {

    if gestureRecognizer.state != UIGestureRecognizerState.began {
        return
    }

    //  your code

If you would like to allow the user to move the pin while touching you will need to switch the gesture recognizer state and update the annotation coordinate if gestureRecognizer.state changes:

func action(_ gestureRecognizer: UIGestureRecognizer) {
    switch gestureRecognizer.state {
    case .began:
        let annotation = MKPointAnnotation()
        annotation.coordinate = mapView.convert(gestureRecognizer.location(in: mapView), toCoordinateFrom: mapView)
        annotation.title =  "Untitled"
        mapView.addAnnotation(annotation)
    case .changed:
        if let annotation = (mapView.annotations.filter{$0.title! == "Untitled" }).first as? MKPointAnnotation {
            annotation.coordinate =  mapView.convert(gestureRecognizer.location(in: mapView), toCoordinateFrom: mapView)
        }
    case .cancelled:
        if let annotation = (mapView.annotations.filter{$0.title! == "Untitled" }).first as? MKPointAnnotation {
            mapView.removeAnnotation(annotation)
        }
    // you can also prompt the user here for the annotation title
    case .ended:
        if let annotation = (mapView.annotations.filter{$0.title! == "Untitled" }).first as? MKPointAnnotation {
            let alert = UIAlertController(title: "New Annotation", message: "", preferredStyle: .alert)
            var inputTextField: UITextField?
            alert.addAction(UIAlertAction(title: "Add", style: .default) { _ in
                if  let annotationTitle = inputTextField?.text {
                    annotation.title =  annotationTitle
                    annotation.subtitle = "Lat:\(String(format: "%.06f", annotation.coordinate.latitude))  Lon:\(String(format: "%.06f", annotation.coordinate.longitude))"
                }
            })
            alert.addTextField(configurationHandler: { textField in
                textField.placeholder = "Place Description"
                inputTextField = textField
            })
            alert.addAction(UIAlertAction(title: "Cancel", style: .cancel){ _ in
                self.mapView.removeAnnotation(annotation)
            })
            present(alert, animated: true, completion: nil)
        }
    default:
        print("default")
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!