获取注释图钉点击事件 MapKit Swift

Kwn*_*ios 2 mkmapview mkannotation ios swift swift3

我有一个类的数组。并在 mkmapview 中添加一些注释引脚。

var events = [Events]()

   for event in events {
        let eventpins = MKPointAnnotation()
        eventpins.title = event.eventName
        eventpins.coordinate = CLLocationCoordinate2D(latitude: event.eventLat, longitude: event.eventLon)
        mapView.addAnnotation(eventpins)
    }
Run Code Online (Sandbox Code Playgroud)

通过地图的委托,我实现了一个功能

 func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    print(view.annotation?.title! ?? "")
}
Run Code Online (Sandbox Code Playgroud)

如何获取events正在点击数组的哪一行?因为我想在另一个 ViewController 中继续,并且我想发送这个类对象。

And*_*jen 5

您应该创建一个自定义注释类,例如:

class EventAnnotation : MKPointAnnotation {
    var myEvent:Event?
}
Run Code Online (Sandbox Code Playgroud)

然后,当您添加注释时,您将Event与自定义注释链接:

for event in events {
    let eventpins = EventAnnotation()
    eventpins.myEvent = event // Here we link the event with the annotation
    eventpins.title = event.eventName
    eventpins.coordinate = CLLocationCoordinate2D(latitude: event.eventLat, longitude: event.eventLon)
    mapView.addAnnotation(eventpins)
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以在委托函数中访问该事件:

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    // first ensure that it really is an EventAnnotation:
    if let eventAnnotation = view.annotation as? EventAnnotation {
        let theEvent = eventAnnotation.myEvent
        // now do somthing with your event
    }
}
Run Code Online (Sandbox Code Playgroud)