在 iOS 11 中,Apple 还在 MKMapViewDelegate 中引入了新的回调:
func mapView(_ mapView: MKMapView, clusterAnnotationForMemberAnnotations memberAnnotations: [MKAnnotation]) -> MKClusterAnnotation
在注解聚集之前,将调用此函数来为memberAnnotations 请求MKClusterAnnotation。所以第二个参数memberAnnotations表示要聚类的注解。
编辑(2018 年 4 月 1 日):
集群标注有两个关键步骤:
首先,在注解聚集之前,MapKit 调用mapView:clusterAnnotationForMemberAnnotations: 函数为memberAnnotations 请求一个MKClusterAnnotation。
其次,MapKit 将 MKClusterAnnotation 添加到 MKMapView 中,会调用mapView:viewForAnnotation: 函数生成一个 MKAnnotationView。
因此您可以在两个步骤中的任何一个中取消选择注释,如下所示:
var selectedAnnotation: MKAnnotation? //the selected annotation
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
}
}
}
//...
}