Swift - Using a UISwitch to change Pin Color

405 Views Asked by At

I want to change the pin color from Red to Purple once the switch has been turned on. So far I have tried:

@IBAction func SwitchChanged(_ sender: Any){
  if LegacySwitch.isOn == true {
   annotation.pinTintColor = .purple
  } else {
   annotation.pinTintColor = .red
  }
}

My switch is connected with:

@IBOutlet weak var LegacySwitch: UISwitch!

I created my pin in my ViewDidLoad. The coordinates of the pin come from another ViewController.

//Map Stuff
    let Coordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    annotation.coordinate = Coordinates
    LocationMap.addAnnotation(annotation)
    let center = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
    self.LocationMap.setRegion(region, animated: true)

When ever I run the app, the pin continues to be red. The Action is encountered as I used a breakpoint to tell me it ran.

EDIT I forgot to mention, I created the annotation variable above the ViewDidLoad.

var annotation = MyPointAnnotation()

I also have a MKPointAnnotation Class

class MyPointAnnotation: MKPointAnnotation {
    var pinTintColor: UIColor?
}

Things that did not work:

 func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")
    if LegacySwitch.isOn {
        annotationView.pinTintColor = .purple
    } else {
        annotationView.pinTintColor = .red
    }

    return annotationView
}
1

There are 1 best solutions below

5
matt On

Distinguish between:

  • An annotation: a lightweight bundle of characteristics

  • An annotation view: what you see, supplied on the basis of the annotation through a call to the map view delegate's mapView(_:viewFor:).

You are changing the former but not the latter. All the action in that regard happens in mapView(_:viewFor:), but you have not shown that — nor is there any particular reason why it would be called just because you change a property of an annotation sitting off in an instance variable somewhere. You need to replace the annotation in the map, so as to get the annotation view to be regenerated.