2017-03-06 100 views
2

我有一個類的數組。並在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中,我想發送這個類對象。

回答

3

你應該創建一個自定義的註釋類,如:

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

正是我在找的東西! –