How to prevent custom MKAnnotationViews from reverting back to using the default color and glyph image?

Viewed 174

I have a few MKMapViews on separate tabs of a UITabBarController. Each map uses custom MKAnnotationViews for MKAnnotations and MKClusterAnnotations. The custom MKAnnotationViews are green with star glyph or green with a number if it's for a cluster.

The problem is that my custom MKAnnotationViews are randomly reverting back to the default appearance of red with a pin glyph. When I zoom in, the views will start to redraw and be right. I haven't been able to consistently reproduce the issue, but it seems to occur when I navigate away from a tab then return.

Is there a way to force a reload on map view similar to reloadData() on a collection view? My viewForAnnotation func shouldn't ever return nil so I don't know how this could be happening.

 func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
     var view = mapView.dequeueReusableAnnotationView(withIdentifier: "CustomAnnotationView") as? CustomAnnotationView
     if view == nil {
         view = CustomAnnotationView(annotation: annotation, reuseIdentifier: "CustomAnnotationView")
     } else {
         view?.annotation = annotation
     }
     return view

     // code for the cluster annotations redacted
 }
1 Answers

Problem solved. I, apparently, needed to style the markers in the prepareForReuse function on the cluster subclasses.

override func prepareForReuse() {
    super.prepareForReuse()

    style()
}
Related