Swift - passing data from mapkit annotation to another view by disclosure button

Leszek picture Leszek · Oct 24, 2014 · Viewed 7.3k times · Source

I have a map with annotations, after clicking the pin, the callout shows with title of annotation and a disclosure button. When I tap button the segue is triggered and I move to another view. How to determine what annotation was clicked, or pass the title to another view.

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)
            pinView!.canShowCallout = true
            pinView!.animatesDrop = true
            pinView!.pinColor = .Red

            var calloutButton = UIButton.buttonWithType(.DetailDisclosure) as UIButton
            pinView!.rightCalloutAccessoryView = calloutButton
        } else {
            pinView!.annotation = annotation
        }
        return pinView!
}

func mapView(mapView: MKMapView!, annotationView: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

    if control == annotationView.rightCalloutAccessoryView {
        performSegueWithIdentifier("Detail", sender: self)
    }
}

Thanks

Answer

codester picture codester · Oct 24, 2014

You can use MKAnnotation title of annotation property for finding the pins if annotation title is different

 annotationView.annotation.title

return String.Compare String to differenciate.

or

Use tag property in pinview

pinView!.tag //set tag for each pin in `viewForAnnotation` method

In

func mapView(mapView: MKMapView!, annotationView: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

    //get tag here
      if(annotationView.tag == 0){
        //Do for 0 pin
     }

    if control == annotationView.rightCalloutAccessoryView {
        performSegueWithIdentifier("Detail", sender: self)
    }
}