简体   繁体   中英

change UIImage from MKAnnotation in the MKMapView

I have a mapView with only on MKAnnotation, that has a costume image. When the user changes the mapType, I need to change the image of that annotation.

The way I did that was to remove the annotation from the map, and insert another with the correct image, bu i don't think is the best way. It takes about 1 ou 2 seconds to show the new image.

How can I do it without remove the annotation and drop another?

Thanks,

RL

You can use the viewForAnnotation: instance method of the map view (not the same as its delegate method with a similar name) to get the current view of the annotation and force the image change explicitly.

For example, at the place where the map type is changed:

MKAnnotationView *av = [mapView viewForAnnotation:annotation];

if (mapView.mapType == MKMapTypeHybrid)
    av.image = [UIImage imageNamed: @"hybrid.png"];
else
    av.image = [UIImage imageNamed: @"standard.png"];

However, you should add the exact same if-statement to the viewForAnnotation delegate method also so when the map view later calls the delegate method itself, it will set the correct image also.

You may want to move the image-setting logic to a common method that you can call from the place where you change the map type and from the viewForAnnotation delegate method (the MKAnnotationView object would be passed as a parameter). If the logic is in one place, you don't have to remember to keep both places in sync.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM