获取注释引脚点击事件MapKit Swift

时间:2017-03-06 19:44:11

标签: ios swift swift3 mkmapview mkannotation

我有一个班级的数组。在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)
    }

通过地图代表,我实现了一项功能

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

如何获取数组events的哪一行? 因为我想在另一个ViewController中进行segue,我想发送这个Class Object。

1 个答案:

答案 0 :(得分:4)

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

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