如何在MKPointAnnotation中设置标识符

时间:2017-02-13 11:09:29

标签: ios swift mapkit

我正在尝试制作许多不同类型的注释。所有注释都需要根据美丽的原因进行自定义。

我知道需要使用viewFor Annotation,但我怎么知道注释的类型呢?

enter image description here

func addZoneAnnotation() {

    let zoneLocations = ZoneData.fetchZoneLocation(inManageobjectcontext: managedObjectContext!)

    for zoneLocation in zoneLocations! {

        let zoneCoordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: Double(zoneLocation["latitude"]!)!, longitude: Double(zoneLocation["longitude"]!)!)

        let zoneAnnotation = MKPointAnnotation()
        zoneAnnotation.coordinate = zoneCoordinate


        map.addAnnotation(zoneAnnotation)

    }

}

1 个答案:

答案 0 :(得分:0)

子类MKPointAnnotation添加您想要的任何属性:

class MyPointAnnotation : MKPointAnnotation {
    var identifier: String?
}

然后你可以按照以下方式使用它:

func addZoneAnnotation() {
    let zoneLocations = ZoneData.fetchZoneLocation(inManageobjectcontext: managedObjectContext!)

    for zoneLocation in zoneLocations! {
        let zoneCoordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: Double(zoneLocation["latitude"]!)!, longitude: Double(zoneLocation["longitude"]!)!)
        let zoneAnnotation = MyPointAnnotation()
        zoneAnnotation.coordinate = zoneCoordinate
        zoneAnnotation.identifier = "an identifier"

        map.addAnnotation(zoneAnnotation)
    }
}

最后当你需要访问它时:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    guard let annotation = annotation as? MyPointAnnotation else {
        return nil
    }

    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "reuseIdentifier")
    if annotationView == nil {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "reuseIdentifier")
    } else {
        annotationView?.annotation = annotation
    }

    // Now you can identify your point annotation 
    if annotation.identifier == "an identifier" {
        // do something
    }

    return annotationView
}