i have an array of a class. and in a mkmapview i append some annotation pins.
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)
}
With the delegate of map i've implemented a function
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
print(view.annotation?.title! ?? "")
}
How can I get which row of the array events
is being tapped?
Because i want to segue in another ViewController and i would like to send this Class Object.
You should create a custom annotation class, like:
class EventAnnotation : MKPointAnnotation {
var myEvent:Event?
}
Then, when you add your annotations, you'll link the Event
with the custom annotation:
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)
}
Now, you can access the event in the delegate function:
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
}
}