I have a function for tintColor in my class:
func pinColor() -> UIColor {
switch status.text! {
case "online":
return UIColor(red: 46/255, green: 204/255, blue: 113/255, alpha: 1.0)
default:
return UIColor.red
}
}
Also I have this extension:
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? Marker {
let identifier = "pin"
var view: MKPinAnnotationView
if let dequeuedView = map.dequeueReusableAnnotationView(withIdentifier: identifier)
as? MKPinAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) as UIView
view.pinTintColor = annotation.pinColor()
}
return view
}
return nil
}
}
I load my data with array for mapView every 10 seconds and present it like this:
func mapView() {
map.layoutMargins = UIEdgeInsets(top: 30, left: 30, bottom: 30, right: 30)
map.showAnnotations(markersArrayFiltered!, animated: true)
}
Error: - every time when I load new data, my colors of pins are different but my data does not change.
What did I do wrong?
You are using dequeueReusableAnnotationView
which returns a reusable annotation view located by its identifier.
But you're setting the pin color only for the first time you initialized the MKPinAnnotationView. You must set in both situations. And this isn't only for pin color, for everything that based on a data.
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? Marker {
let identifier = "pin"
var view: MKPinAnnotationView
if let dequeuedView = map.dequeueReusableAnnotationView(withIdentifier: identifier)
as? MKPinAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
}
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) as UIView
view.pinTintColor = annotation.pinColor()
return view
}
return nil
}
}