Swift,如何从点击的自定义注释中获取信息

Big*_*tor 2 annotations mkmapview mkannotationview ios swift

我有以下自定义注释类:

import UIKit
import MapKit

class LocationMapAnnotation: NSObject, MKAnnotation {
    var title: String?
    var coordinate: CLLocationCoordinate2D
    var location: Location

    init(title: String, coordinate: CLLocationCoordinate2D, location: Location) {
        self.title = title
        self.coordinate = coordinate
        self.location = location
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在将注释加载到这样的地图视图中:

for i in 0..<allLocations.count{
            //Add an annotation
            let l: Location = self.allLocations[i] as! Location
            let coordinates = CLLocationCoordinate2DMake(l.latitude as Double, l.longitude as Double)
            let annotation = LocationAnnotation(title: l.name, coordinate: coordinates, location: l)
            mapView.addAnnotation(annotation)
        }
Run Code Online (Sandbox Code Playgroud)

我想Location从选定的注释中获取对象.目前我有这个方法,当我点击注释时调用,但我不确定如何从注释中检索特定对象.

func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
    print("Annotation selected")

    //performSegueWithIdentifier("locationInfoSegue", sender: self)
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Ghu*_*Ali 10

您可以在didSelectAnnotationView中获取Annotation,然后它将为您提供MKAnnotationView.此MKAnnotationView将MKAnnotation作为对象.

func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
    println("Annotation selected")

    if let annotation = view.annotation as? LocationMapAnnotation {
        println("Your annotation title: \(annotation.title)");
    }
}
Run Code Online (Sandbox Code Playgroud)