为什么不调用MKMapView中的clusterAnnotationForMemberAnnotations?
我有一个简单的地图视图:
@IBOutlet private var mapView: MKMapView!
然后我一个接一个地添加注释:
mapView.addAnnotation(Annotation(user: user))
并向他们展示:
mapView.showAnnotations(mapView.annotations, animated: true)
我还实现了这个方法:
func mapView(_ mapView: MKMapView, clusterAnnotationForMemberAnnotations memberAnnotations: [MKAnnotation]) -> MKClusterAnnotation { print(memberAnnotations) return MKClusterAnnotation(memberAnnotations: memberAnnotations) }
但这根本不被召唤。 为什么?
看起来好像需要为MKAnnotationView设置clusteringIdentifier
。 这对我有用:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier, for: annotation) annotationView.clusteringIdentifier = "identifier" return annotationView }
检查
class YourViewController: MKMapViewDelegate {
和
mapView.delegate = self
另见: https : //github.com/artemnovichkov/iOS-11-by-Examples/blob/master/iOS-11-by-Examples/MapKit/MapKitViewController.swift
@ peter的答案对我有用,但我发现直接在MKAnnotationView上设置clusterIdentifier而不是使用委托方法来设置它更直观。例如:
class VehicleAnnotationView: MKAnnotationView { override var annotation: MKAnnotation? { willSet { clusteringIdentifier = "1" canShowCallout = true calloutOffset = CGPoint(x: -5, y: 5) rightCalloutAccessoryView = UIButton(type: .detailDisclosure) image = UIImage(named: "MapVehiclePin") } } }