如何检查注释是否已群集(MKMarkerAnnotationView和Cluster)

时间:2017-12-31 08:03:13

标签: swift mkmapview ios11 mkannotation mkannotationview

我正在尝试使用ios11中添加到mapview的新功能。

我将所有MKAnnotationView与圆形碰撞聚类在一起,但我必须实时检查注释何时聚集。

我不知道该怎么做。

编辑(4/1/2018):

更多信息:当我选择注释时,我会在调用didSelect方法时添加自定义CallOutView,并在调用didDeselect方法时删除CallOut。

问题在于选择注释并成为聚类时,放大注释时仍然会选中注释但是正常"状态。

我想删除我选择的注释的CallOut,当它像didDeselect方法一样聚集时。

下面的屏幕截图来说明我的问题:

1 - Annotation Selected

2 - Annotation Clustered

3 - Annotation Zoom In after cluster

我认为这只是一个理解问题。

任何帮助都会非常感激。 提前谢谢

3 个答案:

答案 0 :(得分:3)

当形成新群集时,将调用mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?来请求该群集的新视图。

你可以像这样检查:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    //...
    if annotation is MKClusterAnnotation {
        //This is your new cluster.
    }
    //Alternatively if you need to use the values within that annotation you can do
    if let cluster = annotation as? MKClusterAnnotation {

    }
    //...
}

答案 1 :(得分:2)

在iOS 11中,Apple还在MKMapViewDelegate中引入了一个新的回调:

MKClusterAnnotation

在注释成为群集之前,将调用此函数为memberAnnotations请求memberAnnotations。因此,名为mapView:clusterAnnotationForMemberAnnotations:的第二个参数表示要聚类的注释。

编辑(4/1/2018):

群集注释有两个关键步骤:

首先,在注释成为聚类之前,MapKit调用memberAnnotations函数为mapView:viewForAnnotation:请求MKClusterAnnotation。

其次,MapKit将MKClusterAnnotation添加到MKMapView,并调用var selectedAnnotation: MKAnnotation? //the selected annotation函数来生成MKAnnotationView。

因此,您可以在以下两个步骤中取消选择注释:

func mapView(_ mapView: MKMapView, clusterAnnotationForMemberAnnotations memberAnnotations: [MKAnnotation]) -> MKClusterAnnotation { for annotation in memberAnnotations { if annotation === selectedAnnotation { mapView.deselectAnnotation(selectedAnnotation, animated: false)//Or remove the callout } } //... }

 func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
     if let clusterAnnotation = annotation as? MKClusterAnnotation {
         for annotation in clusterAnnotation.memberAnnotations {
             if annotation === selectedAnnotation {
                 mapView.deselectAnnotation(selectedAnnotation, animated: false)//Or remove the callout
             }
         }
     }

     //...
 }

或者:

stats

答案 2 :(得分:2)

我在这里参加聚会已经晚了两年,但我想说的是,您还可以通过以下方式检测是否选择了聚类而不是单个注释:

        func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {

            // selected annotation belongs to a cluster
            if view.annotation is MKClusterAnnotation {
                print("selected a cluster")
            }
        }