0
votes

I have tried using the func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) to pass the annotation title to the embedded container view. However when i build and run, it doesn't work.

What am I doing incorrectly? Is this the right approach?

I've tried func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) see code

var annotationTitle = "Default"



func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView){
    if let annotation = view.annotation {
        annotationTitle = annotation.title!!
    }

}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showMapContainer" {
        let destination = segue.destination as! MapDetailContainerViewController
        destination.selectedAnnotation = annotationTitle as String
    }
}

}

The data is being passed to the containerviewcontroller as "Deafult" instead of annotation.title value

1
Thanks for the insight. The container and map are shown at the same time. I want to be able to click the various map pins and have the container show information about the pin currently selected.Freddie726

1 Answers

0
votes

You said:

The container and map are shown at the same time.

If they’re both created at the same time, then prepare(for:sender:) is undoubtedly getting called before didSelect is. You can confirm that with some breakpoints or judicious print statements.

So you can have prepare(for:sender:) save a reference to segue.destination as? MapDetailContainerViewController in some local variable and then didSelect can set selectedAnnotation

var embeddedViewController: MapDetailContainerViewController?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showMapContainer" {
        embeddedViewController = segue.destination as? MapDetailContainerViewController
    }
}

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let annotation = view.annotation,
        let title = annotation.title {
            embeddedViewController?.selectedAnnotation = title
    }
}

Or you can bypass the prepare(for:sender) and just use children (previously called childViewControllers):

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView){
    if let embeddedViewController = children.first as? MapDetailContainerViewController,
        let annotation = view.annotation,
        let title = annotation.title {
            embeddedViewController.selectedAnnotation = title
    }
}