OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在 MKPointAnnotation 中设置标识符 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:56
标题: ios - 如何在 MKPointAnnotation 中设置标识符

我正在尝试制作很多不同类型的注释。出于美观的原因,所有注释都需要自定义。

我知道它需要使用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)

    }

}



Best Answer-推荐答案


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

关于ios - 如何在 MKPointAnnotation 中设置标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42202607/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4