I'm running into an issue with custom annotations displaying incorrectly. In my code, I check whether the current annotation is for a station with a given unique identifier. If so, I customize its properties.
StationAnnotationView.swift
class StationAnnotationView: MKMarkerAnnotationView {
override var annotation: MKAnnotation? {
willSet {
guard let station = newValue as? Station else { return }
clusteringIdentifier = nil
displayPriority = .required
if (station.id == "26") {
glyphText = "p"
markerTintColor = UIColor(named: "Blue")
}
}
}
At first, my mapView
displays the annotations correctly (i.e., changing the color and glyphtext for the only station with station.id == 26
), but after panning and zooming for a while, my custom formatting begins to get applied to other annotations (which shouldn't happen, because there's only one station for any given station.id
). I suspect it's due to the AnnotationView
reusing the annotation. How can I prevent this from happening?
As you said, it's due to the AnnotationView reusing the annotation. Try the following code:
if (station.id == "26") {
glyphText = "p"
markerTintColor = UIColor(named: "Blue")
} else {
glyphText = // Default text
markerTintColor = // Default color
}