How to change non selected annotation pin images on mapkit with Swift

喜夏-厌秋 提交于 2019-12-06 14:53:10

Conform to MKMapViewDelegate protocol and then:

func mapView(mapView: MKMapView!, didSelectAnnotationView view: MKAnnotationView!) {
    let selectedAnnotation = view.annotation
    for annotation in mapView.annotations {
        if let annotation = annotation as? MKAnnotation where !annotation.isEqual(selectedAnnotation) {
            // do some actions on non-selected annotations in 'annotation' var
        }
    }

Also you can save the selected annotation for later use here, if you want to process all annotations in another moment.

finally managed :) solved the problem little bit hard way but working smooth :) thank you for the tip rshev ;)

i used a bool for tap recognize

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {

    if annotation is CustomAnnotation {
        var pin = mapView.dequeueReusableAnnotationViewWithIdentifier(customAnnotationViewIdentifier)
        pin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: customAnnotationViewIdentifier)

        if tapControl {
            pin.image = UIImage(named: "MapAnnotationIcon")
        } else {
            pin.image = UIImage(named: "SelectedMapAnnotationIcon")
        }

        if pin == nil {
            pin.canShowCallout = false
        } else {
            pin.annotation = annotation
        }

        return pin

and when pin tapped ->

  if let annotation = view.annotation as? CustomAnnotation {

        tapControl = !tapControl
        for annotation in mapView.annotations {
            if let annotation = annotation as? MKAnnotation where !annotation.isEqual(selectedAnnotation) {
                mapView.removeAnnotation(annotation)
            }
        }
        addAnnotations()
        println("tapped")

i removed all pins without selected pin, and then draw them back but this time tapcontrol is false so other pins are redrawed with another imageview, so thats what i exactly want to do.

You just have to overrride isSelected property inside your MKAnnotationView subclass.

override var isSelected: Bool {
    didSet {
        if isSelected {
            // do stuff where annotation is selected
        } else {
            // do opposite
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!