在Swift的MapView中检测longpress

问题描述 投票:0回答:1

我在SwiftUi中有一个MapView,当用户长按地图上的某个位置时,我正在尝试向其添加图钉注释。我看到可以轻松快速地完成此操作,但是我正在使用SwiftUI。我不知道如何添加长按检测器。一个代码示例将是不错的。

我的MapView

struct MapView: UIViewRepresentable {

@Binding
var annotations: [PinAnnotation]
let addAnnotationListener: (PinAnnotation) -> Void

func makeUIView(context: Context) -> MKMapView {
    let mapView = MKMapView()
    mapView.delegate = context.coordinator
    return mapView
}

func updateUIView(_ view: MKMapView, context: Context) {
    view.delegate = context.coordinator
    view.addAnnotations(annotations)
    if annotations.count == 1 {
        let coords = annotations.first!.coordinate
        let region = MKCoordinateRegion(center: coords, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
        view.setRegion(region, animated: true)
    }

}


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

}

MapViewCoordinator

class MapViewCoordinator: NSObject, MKMapViewDelegate {

var mapViewController: MapView

init(_ control: MapView) {
    self.mapViewController = control
}

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    let annotation = view.annotation
    guard let placemark = annotation as? MKPointAnnotation else { return }
}

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?{
    //Custom View for Annotation
    let identifier = "Placemark"
    if  let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) {
        annotationView.annotation = annotation
        return annotationView
    } else {
        let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        annotationView.isEnabled = true
        annotationView.canShowCallout = true
        let button = UIButton(type: .infoDark)
        annotationView.rightCalloutAccessoryView = button
        return annotationView
    }
}
}
ios swift swiftui mapkit
1个回答
0
投票

查找下面提供的代码的修改部分以获取所需的行为:

struct SUMapView: UIViewRepresentable {

    // ... other your code here

    func makeUIView(context: Context) -> MKMapView {
        let mapView = MKMapView()
        mapView.delegate = context.coordinator

        let longPressed = UILongPressGestureRecognizer(target: 
              context.coordinator, action: #selector(addPin(gesture:)))
        mapView.addGestureRecognizer(longPressed)

        return mapView
    }

    // ... other your code here
}

class MapViewCoordinator: NSObject, MKMapViewDelegate {

    // ... other your code here

    @objc func addPin(gesture: UILongPressGestureRecognizer) {
        // do whatever needed here
    }

    // ... other your code here

}
© www.soinside.com 2019 - 2024. All rights reserved.