Kevin
Kevin

Reputation: 1189

Swift 3.0 Update Annotation on Pin

I have an annotation on my pins for my mapView. On my annotation, I have a button and I want to be able to change the button image (from plus to minus) when the user clicks on the button. I am not sure where I can update this. I currently have my button image set up when the user clicks on the pin. The image itself won't update until I reload the map, but I am looking to update the button on the annotation view immediately after the user clicks on it. I am not sure how to update the button while the annotation is popped up.

 func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {

    if let annotation = view.annotation as? MKPointAnnotation {
                let btn = UIButton(type: .detailDisclosure)
                view.rightCalloutAccessoryView = btn
                if annotation.accessibilityValue! == "Minus" {

                    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
                    button.setBackgroundImage(UIImage(named: "minus"), for: .normal)
                    button.addTarget(self, action: #selector(MapVC.minus), for: .touchUpInside)
                    view.leftCalloutAccessoryView = button
                } else {
                    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
                    button.setBackgroundImage(UIImage(named: "plus"), for: .normal)
                    button.addTarget(self, action: #selector(MapVC.plus), for: .touchUpInside)
                    view.leftCalloutAccessoryView = button
                }
    }
}

Upvotes: 0

Views: 320

Answers (1)

Kosuke Ogawa
Kosuke Ogawa

Reputation: 7451

You don't have to use didSelect delegate method. When the user clicks on the button, calloutAccessoryControlTapped delegate method is called. You can change the button image in this delegate method.

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    if control == view.leftCalloutAccessoryView {
        let button = control as! UIButton
        if annotation.accessibilityValue! == "Minus" {
            button.setBackgroundImage(UIImage(named: "minus"), for: .normal)
        } else {
            button.setBackgroundImage(UIImage(named: "plus"), for: .normal)
        }
    }
}

Upvotes: 1

Related Questions