I would like to work with an annotation once it's clicked. I've looked it up on the documentation of Apple and I did googled but I can not find why this is any different than how it should be done.
Basically; I don't get a println("Pin clicked");
Why not?
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView!
{
if !(annotation is MKPointAnnotation) {
return nil
}
let reuseId = "test"
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.canShowCallout = true
}
else {
anView.annotation = annotation
}
return anView
}
func mapView(mapView: MKMapView!, didSelectAnnotationView view: MKAnnotationView!)
{
println("Pin clicked");
}
func setAnnotationPinOnMap(annotation : NSManagedObject)
{
var subject: AnyObject? = annotation.valueForKey("subject")
var desc: AnyObject? = annotation.valueForKey("desc")
var langitude: AnyObject? = annotation.valueForKey("langitude")
var longitude: AnyObject? = annotation.valueForKey("longitude")
println(annotation);
let pin = MKPointAnnotation()
let location = CLLocationCoordinate2D(
latitude: longitude as CLLocationDegrees,
longitude: langitude as CLLocationDegrees
)
println(location.longitude, location.latitude)
pin.setCoordinate(location)
pin.title = subject as String!
pin.subtitle = desc as String!
println( pin.coordinate.longitude)
viewForAnnotation(pin);
mapView.addAnnotation(pin)
}
I have imported map kit and included the map view delegate.
To answer the original question, didSelectAnnotationView
was most likely not getting called because the map view's delegate
property was not set. Another common cause is if the annotation's title
is blank.
In the updated question, the pins won't show with the way viewForAnnotation
is implemented because it creates an MKAnnotationView
but doesn't set its image
property. The image
property of an MKAnnotationView
is nil
by default so the pins are there but invisible.
If you want to display standard red pins, either:
viewForAnnotation
delegate method at all and the map view will display red pins by default.viewForAnnotation
delegate method and create an MKPinAnnotationView
instead which automatically displays a "pin" image.So either set the pin's image
to some custom image:
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.canShowCallout = true
anView.image = UIImage(named:"CustomImage") // <-- add this line
or create an MKPinAnnotationView
instead and optionally set its pinColor
:
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if anView == nil {
anView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView!.canShowCallout = true
anView!.animatesDrop = true
anView!.pinColor = .Purple // or Red or Green
}
else {
anView!.annotation = annotation
}