问题



I need to find a way to change the pin color when the map is loaded by pushing a button from another screen.
For example, the original pins are all red, but when I go to a page and push the map button, it has to lead me to the map view and the coordinates of that location have to be marked with a green pin.
I already have the map set up and the setup of making the pins all red.
Any help is appreciated.
So, just a recap: Page with map with red pin --> click pin, click annotation (another view opens) --> inside view, there is a button (eg. @"change pin color"), click button --> page with map with green pin opens. (Look at the example above with pictures.)
回答1:
What you should do is change something in the data that represents that pin. The annotation. When you switch back to the map the annotation will be redrawn and your viewForAnnotation
method will be called at which point you check the attributes and draw the right colour.
回答2:
Why don't you just declare a new constructor to set the colour of your choice?
// ViewControllerB .h file
@interface ViewControllerB
{
UIColor *pinColor;
}
-(id)initWithPinColor:(UIColor *)chosenPinColor;
...
// ViewControllerB .m file
-(id)initWithPinColor:(UIColor *)chosenPinColor
{
self = [super init];
if(self)
{
pinColor = chosenPinColor;
}
return self;
}
...
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if([annotation isKindOfClass:[MKUserLocation class]])
{
return nil;
}
static NSString *annotationViewID = @"annotationViewID";
MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationViewID];
if(!annotationView)
{
annotationView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationViewID] autorelease];
}
// this will use the pinColor stored in the constructor
annotationView.pinColor = pinColor;
annotationView.canShowCallout = YES;
annotationView.animatesDrop = YES;
annotationView.annotation = annotation;
return annotationView;
}
Then you can simply do this in ViewControllerA:
// ViewControllerA .m file
#import "ViewControllerB.h"
...
-(void)showMapWithPinColor:(id)sender
{
ViewControllerB *vc = [[ViewControllerB alloc] initWithPinColor:[UIColor green]];
[self.navigationController pushViewController:vc animated:YES];
}
来源:https://stackoverflow.com/questions/16677966/change-color-of-pin-on-map-after-pressing-button-on-another-screen