user19406372
user19406372

Reputation: 11

MKMapView refresh map after removing annotation

I have the following function in an extension of MKMapView that let me reload a specific annotation and keep it selected if needed and the issue is every time the self.removeAnnotation is called, the whole map is reloaded (or at least all the pins "jumped" as if a reload occurred)

Is there a way to achieve a reload of a single annotation without having the visual of a whole map reloading ?

 func reloadAnnotation(_ annotation: MKAnnotation, keepSelection: Bool = true) {
        let isSelected = selectedAnnotations.contains(where: annotation.isEqual(_:))
        //already tried **UIView.performWithoutAnimation** which decrease the jumping effect
        // UIView.performWithoutAnimation {
          self.removeAnnotation(annotation)
          self.addAnnotation(annotation)
        // }
        guard isSelected && keepSelection else {
            return
        }
        self.selectedAnnotations.append(annotation)
    }

Upvotes: 1

Views: 507

Answers (1)

Gerd Castan
Gerd Castan

Reputation: 6849

In my experience the unwanted "whole map reloading" visual effect comes from the recalculation of clusters which is triggered by self.removeAnnotation(annotation) and self.addAnnotation(annotation).

So you have to avoid this methods if you just want to update some visual information.

My assumption is that your callout and/or title changed dynamically while selected and you reload because you want to render the changed callout information.

func reloadAnnotation(_ annotation: MKAnnotation, keepSelection: Bool = true) {
    let annotationView = mapView.view(for: annotation) as? MyCoolAnnotationView
    if let annotationView {
        // do stuff like
        annotationView.setNeedsLayout()
    }
}

annotationView will be nil if the annotation is not in the visible region or part of a cluster. In that case you don't want to reload anyways.

Instead of annotationView.setNeedsLayout() you might call your own method that does whatever you want.

Upvotes: 0

Related Questions