change annotation image after its created

2019-02-17 15:32发布

I have a custom annotation that sets its image based on the type of the annotation using the viewForAnnotation delegate method. Im only using 1 annotation that represents a car moving and want to change the image for when the car is detected to be moving and stopped. How could I go about this besides removing my annotation and re-adding it which causes a blink?

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-17 16:15

Wherever you detect that the car's state has changed, retrieve the annotation's current view using the MKMapView instance method viewForAnnotation:. This is not the same as the mapView:viewForAnnotation: delegate method.

After getting the current view for the annotation, you can modify its properties including image.

Also make sure the mapView:viewForAnnotation: delegate method has the same exact condition to set image based on the state of the car annotation. You may want to put the logic in a common method called from both places (where the state changes and the delegate method) so the code isn't duplicated.

For example, where the state changes, you might have:

//carAnnotation is your id<MKAnnotation> object
MKAnnotationView *av = [mapView viewForAnnotation:carAnnotation];
if (carAnnotation.isMoving)
    av.image = [UIImage imageNamed:@"moving.png"];
else
    av.image = [UIImage imageNamed:@"stopped.png"];

The if statement (or whatever logic you have to set image) is the part that should also be in the viewForAnnotation delegate method.

查看更多
登录 后发表回答