Mapkit с LongPressGestureRecognizer работает с перебоями - PullRequest
3 голосов
/ 21 октября 2019

У меня очень простая настройка, где у меня есть MapKit, и я бы хотел иметь возможность добавлять к нему пин-код каждый раз, когда пользователь нажимает на карту долгим нажатием. Это работает нормально для первого контакта. Но если пользователь попробовал другое долгое нажатие (в другом месте), то жест не распознается. В третий раз сработает, в четвертый раз не сработает и т. Д. (Каждая нечетная попытка будет распознана).

У меня есть пример проекта, который демонстрирует это: https://github.com/alexwibowo/SimpleLocationMarker

По сути, мой взглядконтроллер выглядит следующим образом:

class ViewController: UIViewController {

    @IBOutlet weak var mapView: MKMapView! {
        didSet{
            let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.addNewAnnotation(recognizer:)))
            gestureRecognizer.minimumPressDuration = 0.5
            mapView.addGestureRecognizer(gestureRecognizer)
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @objc func addNewAnnotation(recognizer: UILongPressGestureRecognizer){
        if (recognizer.state != .began) {
            return
        }

        let touchPoint = recognizer.location(in: mapView)
        let wayCoords = mapView.convert(touchPoint, toCoordinateFrom: mapView)

        let annotation = MKPointAnnotation()
        annotation.title = "New"
        annotation.coordinate = wayCoords
        mapView.addAnnotation(annotation)
    }
}

extension ViewController: MKMapViewDelegate {

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        let identifier = "locationMarkerIdentifier"
        var view: MKPinAnnotationView

        if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
            as? MKPinAnnotationView {
            dequeuedView.annotation = annotation
            view = dequeuedView
        } else {
            view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            view.annotation = annotation
            view.canShowCallout = true
            view.isDraggable = true
            view.calloutOffset = CGPoint(x: -5, y: 5)
            view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
        }
        return view
    }


}

Я уверен, что это очень простая ошибка, которую я сделал!

1 Ответ

2 голосов
/ 21 октября 2019

Во-первых, установите его делегата на себя.

@IBOutlet weak var mapView: MKMapView! {
    didSet{
        let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.addNewAnnotation(recognizer:)))
        gestureRecognizer.minimumPressDuration = 0.5
        mapView.addGestureRecognizer(gestureRecognizer)
        gestureRecognizer.delegate = self
    }
}

Во-вторых,

extension ViewController : UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}
...