DesignMeetsCode
DesignMeetsCode

Reputation: 23

Pass Annotation Title to View Controller (swift)

I'm having a hard time passing the title of a selected annotation to the segued view controller. I feel like it may be something simple that I need to change, but can't figure it out.

Here is the code to prepare the segue:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if(segue.identifier == "viewDetail"){

        let theDestination : DetailViewController = segue.destinationViewController as! DetailViewController
        theDestination.getName = view.annotation.title!
    }
}

and here is the code to for when the annotation call out is tapped, it performs the segue

   func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
    self.performSegueWithIdentifier("viewDetail", sender: self)

}

the issue is that, in the prepareForSegue function..it doesn't recognize "view.annotation.title!" stating UIView does not have member "annotation".

I know when I println(view.annotation.title!) in the other function, it works

Thanks for the help

Upvotes: 1

Views: 788

Answers (2)

DesignMeetsCode
DesignMeetsCode

Reputation: 23

Thanks for the help, I solved it with a simple line:

annotation = self.map.selectedAnnotations[0] as! MKAnnotation

so that it sends the annotation title of the first selected annotation in the view, which is only one..the one I called.

Upvotes: 0

hennes
hennes

Reputation: 9342

You need to pass view in the sender parameter of performSegueWithIdentifier in the map view delegate method.

func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
    self.performSegueWithIdentifier("viewDetail", sender: view)
}

Afterwards you can read it out of the sender parameter in the implementation of prepareForSegue.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if(segue.identifier == "viewDetail"){
        let theDestination : DetailViewController = segue.destinationViewController as! DetailViewController
        theDestination.getName = (sender as! MKAnnotationView).annotation!.title!
    }
}

Upvotes: 1

Related Questions