How to add gestures to MapView in SwiftUI

Viewed 1035

I am trying to add gestures (tap, swipe, etc) to a Mapkit Map View in ContentView.swift to no avail. I started with googlemaps and then tried Mapkit. There are two ways I know of to add gestures to a view.

  1. Add gestures to mapView like the following:
import SwiftUI

struct ContentView: View {
    var body: some View {

            MapView()
            .onTapGesture(count: 2) {
                print("Double tapped!")
            }
            .edgesIgnoringSafeArea(.all)
    }
  1. Add gestures in MapView view as follows:
struct MapView: UIViewRepresentable {

    func makeUIView(context: Context) -> MKMapView {
        let mapView = MKMapView()
        mapView.delegate = context.coordinator
        let tap = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.doubleTapped))
        tap.numberOfTapsRequired = 2
        mapView.addGestureRecognizer(tap)
        return mapView
    }

    func updateUIView(_ view: MKMapView, context: Context) {

    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, MKMapViewDelegate {
        var parent: MapView

        init(_ parent: MapView) {
            self.parent = parent
        }

        @objc func doubleTapped() {
            print("Double Tapped...")
        }
    }
}

Neither of these methods seem to work. The preferrable way to me is #1 but I tried an alternate way as in #2. Any ideas on what I am doing wrong? I am using Xcode 11.4 (11E146).Thanks!

0 Answers
Related