Cover by Vandad Nahavandipoor

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

6.5. Displaying Pins with Different Colors on a Map View

Problem

The default color for pins dropped on a map view is red. You want to be able to display pins in different colors in addition to the default color.

Solution

Return instances of MKPinAnnotationView to your map view through the mapView:viewForAnnotation: delegate method.

Every annotation that is added to an instance of MKMapView has a corresponding view that gets displayed on the map view. These views are called annotation views. An annotation view is an object of type MKAnnotationView, which is a subclass of UIView. If the delegate object of a map view implements the mapView:viewForAnnotation: delegate method, the delegate object will have to return instances of the MKAnnotationView class to represent (and optionally, customize) the annotation views to be displayed on a map view.

Discussion

To set up our program so we can customize the color (choosing from the default SDK pin colors) of the annotation view that gets dropped on a map view to represent the annotation, we must return an instance of the MKPinAnnotationView class instead of an instance of MKAnnotationView in the mapView:viewForAnnotation: delegate method. Bear in mind that the MKPinAnnotationView class is a subclass of the MKAnnotationView class.

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{ MKAnnotationView *result = nil; if ([annotation isKindOfClass:[MyAnnotation class]] == NO){ return result; } if ([mapView ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required