Update title/subtitle for custom annotation on an

2020-07-27 02:48发布

问题:

I created a custom annotation to display my data. The data comes from moving vehicles and I've got to update their location on the map as well as their title (it shows the last update time).

My first approach was to simply remove all annotations and recreate them. However this leads to a lot of horrible flickering (the map clears, and then all annotations appear again) and the map blocks while it redraws. Less than optimal solution.

In the OS4 SDK they improved the MKMapViewAnnotation and I can now set the coordinates (they were readonly before). Changing the coordinates moves the view nicely where it should be without any flickering. That solved one of my issues.

It said in the API documentation that changing the title of the MKAnnotation will update the MKAnnotationView. Indeed that's the case for the MKPinView. If I update the MKAnnotation's coordinates and title, the pin moves and shows the new data.

How can I achieve the same result using my custom MKAnnotationView? I can't see any way to ask the view to refresh. I tried calling setNeedsLayout on the MKAnnotationView but that only resulted in the view disappearing.

Cheers.

回答1:

MKMapView uses KVO to observe changes to the title and subtitle properties. The easiest way to ensure the map view notices your changes, is to make them properties and use the setTitle: / setSubtitle: methods (or self.title = @"..."; — note that the self. notation is required):

CustomAnnotation.h

@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;

- (void)changeAnnotation;

CustomAnnotation.m

@synthesize title, subtitle;

- (void)changeAnnotation {
    self.title = @"New title!";
    [self setSubtitle:@"New subtitle!"];
}

The synthesized property setters handle the rigors of key-value observing for you. Otherwise, you'll have to call willChangeValueForKey: and didChangeValueForKey: yourself; these are implemented in NSObject:

[self willChangeValueForKey:@"title"];
[title release];
title = @"New title.";
[self didChangeValueForKey:@"title"];


回答2:

Tried setNeedsDisplay?