Swift, How to get information from a custom annotation on clicked

余生颓废 提交于 2019-12-04 01:51:09

问题


I've got the following custom annotation class:

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

I am loading the annotations into a map view like this:

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

And I am wanting to get the Location object from the selected annotation. Currently I have this method which is called when ever I tap an annotation, but I am unsure how to retrieve the specific object from the annotation.

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

    //performSegueWithIdentifier("locationInfoSegue", sender: self)
}

Thanks.


回答1:


You can get your Annotation within didSelectAnnotationView, which will then give you MKAnnotationView. This MKAnnotationView has MKAnnotation as an object.

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

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


来源:https://stackoverflow.com/questions/37320485/swift-how-to-get-information-from-a-custom-annotation-on-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!