Customizing the Tint Color of Pins on the Map - Maps and Location - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 8. Maps and Location

8.3 Customizing the Tint Color of Pins on the Map

Problem

You want to set the tint color of pin annotations on your map manually.

Solution

Use the pinTintColor property of the MKPinAnnotationView class like so:

let view = MKPinAnnotationView(annotation: annotation,

reuseIdentifier: color.toString())

view.pinTintColor = color

Discussion

Let’s check out an example. Create a single view controller project and dump a map view on top of your view. Make sure that you set the delegate of this map view to your view controller. Also link it to a variable named map in your view controller.

In the view controller, we are going to create annotations with reusable identifiers, so let’s use the color as the ID:

import MapKit

extension UIColor{

final func toString() -> String{

var red = 0.0 as CGFloat

var green = 0.0 as CGFloat

var blue = 0.0 as CGFloat

var alpha = 0.0 as CGFloat

getRed(&red, green: &green, blue: &blue, alpha: &alpha)

return "\(Int(red))\(Int(green))\(Int(blue))\(Int(alpha))"

}

}

Now we create our annotation:

class Annotation : NSObject, MKAnnotation{

var coordinate: CLLocationCoordinate2D

var title: String?

var subtitle: String?

init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String){

self.coordinate = coordinate

self.title = title

self.subtitle = subtitle

}

}

Now ensure that your view controller conforms to the MKMapViewDelegate protocol, define the location that you want to display on the map, and create an annotation for it:

let color = UIColor(red: 0.4, green: 0.8, blue: 0.6, alpha: 1.0)

let location = CLLocationCoordinate2D(latitude: 59.33, longitude: 18.056)

lazy var annotations: [MKAnnotation] = {

return [Annotation(coordinate: self.location,

title: "Stockholm Central Station",

subtitle: "Stockholm, Sweden")]

}()

When your view appears on the screen, add the annotation to the map:

override func viewDidAppear(animated: Bool) {

super.viewDidAppear(animated)

map.removeAnnotations(annotations)

map.addAnnotations(annotations)

}

And when the map view asks for an annotation view for your annotation, return an annotation view with the custom color (see Figure 8-2):

func mapView(mapView: MKMapView,

viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {

let view: MKPinAnnotationView

if let v = mapView.dequeueReusableAnnotationViewWithIdentifier(

color.toString()) where v is MKPinAnnotationView{

view = v as! MKPinAnnotationView

} else {

view = MKPinAnnotationView(annotation: annotation,

reuseIdentifier: color.toString())

}

view.pinTintColor = color

return view

}

Figure 8-2. Our custom color pin is displayed on the map

See Also