Search code examples
iosswiftxcodemkmapview

Change custom image on EXISTING MKAnnotation


I have a simple screen with a mapview, onto which I've added a couple of custom annotations in the typical way. I have a need now to go back and change the image when certain events happen; essentially just changing image to show a little flag indicating that particular annotation has more data available that the user may elect to tap.

What I think I have to do is remove the annotation in question, copy all its data to a new one with a new image, and then re-add it, thus employing viewFor annotation and checking for the updated nature of the annotation's underlying data.

Seems a bit overwrought.

Is there no way to simply say something like:

for var ann in self.eventMap.annotations {
    if let ann2 = ann as? CustomPointAnnotation { // custom type with properties
        if "myCustomIdValueHere" == ann2.myCustomId {
            // found it.
            print( "Found the one I'm looking for" )

            // then change its image from "[existingImageName]" to "[existingImageName]Attention"
        }
    }
}

Solution

  • You can get specific MKAnnotationView with view(for: ) method. Try the following code:

    for var ann in self.eventMap.annotations {
        if let ann2 = ann as? CustomPointAnnotation { // custom type with properties
            if "myCustomIdValueHere" == ann2.myCustomId {
                // found it.
                print( "Found the one I'm looking for" )
    
                // then change its image from "[existingImageName]" to "[existingImageName]Attention"
                let annotationView = self. eventMap.view(for: ann2)
                annotationView?.image = UIImage(named: "[existingImageName]Attention")            }
        }
    }