Luk579 Luk579 - 5 months ago 33
Swift Question

Pass Object to Custom Annotation View

I have a Realm object

Place
with name, description, and coordinate objects. When the
mapView
is loaded, a pin is created for each instance of the Realm object. What I want to achieve is that when you click on the annotation of each pin you will come to a detail view giving you more information about the place. Is there a way to pass this Place object to the custom annotation so I can use its attributes in the
prepareForSegue
function and access and manipulate them in the
DetailViewController
?

Here's my
CustomAnnotation
class:

import Foundation
import UIKit
import MapKit
import RealmSwift

class CustomAnnotation: MKPointAnnotation {
var place = Place()
}


And here the functions in the
ViewController
with the
mapView
:

func loadLocations() {
for place in realm.objects(Place) {
let userLocationCoordinates = CLLocationCoordinate2DMake(place.latitude, place.longitude)
let pinForUserLocation = CustomAnnotation()
pinForUserLocation.coordinate = userLocationCoordinates
pinForUserLocation.title = place.name
pinForUserLocation.subtitle = place.placeDescription
pinForUserLocation.place = place
mapView.addAnnotation(pinForUserLocation)
mapView.showAnnotations([pinForUserLocation], animated: true)
}
}

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if !(annotation is CustomAnnotation) {
return nil
}
let reuseId = "customAnnotation"
var view = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if view == nil {
view = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
view!.image = UIImage(named:"locationAnnotation")
view!.leftCalloutAccessoryView = UIButton(type: UIButtonType.DetailDisclosure)
view!.canShowCallout = true
}
else {
view!.annotation = annotation
}
return view
}

func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
performSegueWithIdentifier("showPlaceDetailSegue", sender: annotation)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showPlaceDetailSegue" {
let vc = segue.destinationViewController as! PlaceDetailViewController
vc.name = sender!.title
vc.descriptionText = sender!.subtitle
vc.coordinate = sender!.coordinate
vc.place = sender!.place
}
}

Answer

Access to annotation by view.annotation and cast it to your custom class in

func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
let annotation = view.annotation as! CustomAnnotation
    performSegueWithIdentifier("showPlaceDetailSegue", sender: annotation)
}