获取注释针点击事件MapKit Swift

问题描述:

我有一个类的数组。并在mkmapview我附加一些注释引脚。获取注释针点击事件MapKit Swift

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) 
    } 

随着地图的代表我已经实现了一个功能

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

我怎样才能获得该阵列events的行被窃听? 因为我想继续在另一个ViewController中,我想发送这个类对象。

你应该创建一个自定义的注释类,如:

class EventAnnotation : MKPointAnnotation { 
    var myEvent:Event? 
} 

然后,当你添加注释,你会与自定义注释链接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) 
} 

现在,你可以在代表功能中访问该事件:

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 
    } 
} 
+0

正是我在找的东西! –