【问题标题】:Set glyphText of MKMarkerAnnotationView for MKClusterAnnotation为 MKClusterAnnotation 设置 MKMarkerAnnotationView 的 glyphText
【发布时间】:2018-06-12 09:12:34
【问题描述】:

我有一个实现 MKAnnotation 协议的类 MapItem。我正在使用 MKMarkerAnnotationView 在地图上显示注释。

根据文档, MKMarkerAnnotationView 的 glyphText 属性设置为 nil 时,它会在标记上生成图钉图像。

在对注释进行聚类时,我希望标记上使用相同的图钉图像。但系统默认将此设置为在此聚类中聚类的注释数。

我什至尝试将此属性设置为零,但没有效果。

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if let item = annotation as? MapItem {
        let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "mapItem") as? MKMarkerAnnotationView
            ?? MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "mapItem")

        annotationView.annotation = item
        annotationView.glyphText = nil
        annotationView.clusteringIdentifier = "mapItemClustered"

        return annotationView
    } else if let cluster = annotation as? MKClusterAnnotation {
        let clusterView = mapView.dequeueReusableAnnotationView(withIdentifier: "clusterView") as? MKMarkerAnnotationView
            ?? MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "clusterView")

        clusterView.annotation = cluster
        clusterView.glyphText = nil

        return clusterView
    } else {
        return nil
    }
}

【问题讨论】:

  • 据我所知,MKMarkerAnnotationView 在集群时严重损坏。似乎没有任何方法可以更改 glyphImage 或 glyphText。使用普通的旧 MKAnnotationView 时,您可以设置自定义图像,但无法自定义标记。有人找到解决办法了吗?

标签: swift mapkit ios11 mkannotationview


【解决方案1】:

这就是我的做法:

class POIMarkerClusterView: MKMarkerAnnotationView {

    override var annotation: MKAnnotation? {
        willSet {
            update(newValue: newValue)
        }
    }

    private func update(newValue: MKAnnotation?) {
        if let cluster = newValue as? MKClusterAnnotation {

            self.image = POIClusterImage(poiStatistics: poiStatistics, count: count)

            // MKMarkerAnnotationView's default rendering usually hides our own image.
            // so we make it invisible:
            self.glyphText = ""
            self.glyphTintColor = UIColor.clear
            self.markerTintColor = UIColor.clear
        }
    }

}

这意味着你可以设置一个任意的图像来渲染为注解视图。我动态创建图像,但您可以从MKMarkerAnnotationView 借用图像并将其设置在此处,因此它看起来像您想要的图钉。

主要技巧是使用UIColor.clear 隐藏您不想看到的内容。

【讨论】:

    猜你喜欢
    • 2020-04-19
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    相关资源
    最近更新 更多