Reputation: 38
I've add several annotations with custom annotation view, but I have a reference only to the marker and not to the annotation view itself. So how can I change the annotation view elements?
Upvotes: 2
Views: 803
Reputation: 2331
I added all my annotation views to a dictionary
I created a global dictionary variable
var annotationViews = [CustomAnnotation:CustomAnnotationView]()
Then after creating each annotation view within my delegate function
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView?
I added it into my dictionary
let annotationView = MyAnnotationView(reuseIdentifier: rid, size: CGSize(width: 45, height: 45), annotation: annotation)
annotationViews[annotation as! MyAnnotation] = annotationView
Later when I wanted to change the text of a text view within my annotation view, I used my annotation in the dictionary call. This returned the annotation view that corresponded to it.
self.annotationViews[anno]?.textView.text = "My new text view status"
No deleting and re-adding required.
You could probably insert something smaller as the key for the dictionary, like annotation.uid or annotation.name or something. I just used the whole annotation object though
Upvotes: 0
Reputation: 72
You should store the annotations in a variable and when you want to change their views just remove them from the map with mapView.removeAnnotation(...) and add it back again with mapView.addAnnotation(...).
The method
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
}
will be called and you should return your changed view.
Pay attention to the fact that for performance reasons you should not use addAnnotation() or removeAnnotation() if you have a lot of annotations, but instead addAnnotations() and removeAnnotations()
Upvotes: 4