A better approach is to use a custom annotation class that implements the MKAnnotation
protocol (an easy way to do that is to subclass MKPointAnnotation
) and add whatever properties are needed to help implement the custom logic.
In the custom class, add a property, say pinColor
, which you can use to customize the color of the annotation.
This example subclasses MKPointAnnotation:
import UIKit
import MapKit
class ColorPointAnnotation: MKPointAnnotation {
var pinColor: UIColor
init(pinColor: UIColor) {
self.pinColor = pinColor
super.init()
}
}
Create annotations of type ColorPointAnnotation
and set their pinColor
:
let annotation = ColorPointAnnotation(pinColor: UIColor.blueColor())
annotation.coordinate = coordinate
annotation.title = "title"
annotation.subtitle = "subtitle"
self.mapView.addAnnotation(annotation)
In viewForAnnotation, use the pinColor
property to set the view's pinTintColor
:
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
let colorPointAnnotation = annotation as! ColorPointAnnotation
pinView?.pinTintColor = colorPointAnnotation.pinColor
}
else {
pinView?.annotation = annotation
}
return pinView
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…