Search code examples
swiftmkmapviewmkannotationview

Re-registering an AnnotationView


A and B are different kinds of MKMarkerAnnotationView classes. In my MapViewController I register A like this:

override func viewDidLoad() {
    super.viewDidLoad()
    mapView.delegate = self

    mapView.register(A.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)

    for annotation in annotations {
        mapView.addAnnotation(annotation)
    }
}

I have a UISwitch that I want to use to change the registered AnnotationView from A to B.

@IBAction func didToggleSwitch(_ sender: Any) {

    mapView.register(B.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)

    // remove all annotations
    mapView.removeAnnotations(mapView.annotations)

    //populate all annotations
    for annotation in annotations {
        mapView.addAnnotation(annotation)
    }

}

The registered view isn't being updated. Any ideas why?

Edit: I've noticed that when I zoom out and pan the map around, some annotations update to the new AnnotationView, and some don't. I suspect this is due to using a reuseIdentifier. How do I get all annotations to conform to the new AnnotationView?


Solution

  • I figured it out. I created a boolean within my MKAnnotation class and configured the annotation properties within annotationView A based on that boolean. When I hit the UISwitch, I loop through all my annotation objects, toggle their boolean's value, and re-register the annotationView, and load them up.