ios - 如何在 MKPointAnnotation 中设置标识符

标签 ios swift mapkit

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

我知道需要使用viewFor注解,但是我怎么知道该注解是什么样的呢?

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)

    }

}

最佳答案

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

相关文章:

ios - 输入字段阻止页面在 iphone 上滚动

ios - 快速下拉文本对齐

ios - 在 iOS 开发的上下文中,什么是配置/makefile 脚本的好书或引用?

ios - MKAnnotation swift

iphone - 如何更改自定义 MKAnnotationView 的框架位置?

iphone - 在 map View 上拖动自定义图钉

ios - 使用 ScaleAspectFit 时,在自定义单元格中创建 UIImageView 会留下旧图像中的伪影

ios - 我如何计算包含特定艺术家的文件?

ios - Cell 的附件不断截断 UILabel

ios - map View 未显示注释点