简体   繁体   中英

Changing pin color MKMapView

I add annotations to my map in this way:

MyAnnotation *annotationPoint2 = [[MyAnnotation alloc] init];
annotationPoint2.coordinate = anyLocation;
annotationPoint2.title = [NSString stringWithFormat:@"%@", obj];
annotationPoint2.subtitle = @"";  //or set to nil
annotationPoint2.keyValue = [NSString stringWithFormat:@"%@", key];
[mapPins addAnnotation:annotationPoint2];

The pins are all red, and I would like them all green. How can I change the color? I have tried the following, but it still gives a red mark:

annotationPoint2.pinColor = MKPinAnnotationColorGreen;
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation 
  {
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"pin"];
    annView.pinColor = MKPinAnnotationColorGreen;
    return annView;
  }

The pinColor property is defined in the MKPinAnnotationView class (not the MKAnnotation protocol).

You create a MKPinAnnotationView in the viewForAnnotation delegate method. If you haven't implemented that delegate, you get standard red pins by default.

In that delegate method, you create an instance of MKPinAnnotationView and you can set its pinColor to green.

Swift3 is in this way:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")

    if annotation.title! == "My Place" {

        annotationView.pinTintColor = UIColor.green

    } else {

        annotationView.pinTintColor = UIColor.red
    }


    return annotationView
}

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