Luk579 Luk579 - 2 years ago 114
Swift Question

Pass Object to Custom Annotation View

I have a Realm object

with name, description, and coordinate objects. When the
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
function and access and manipulate them in the

Here's my

import Foundation
import UIKit
import MapKit
import RealmSwift

class CustomAnnotation: MKPointAnnotation {
var place = Place()

And here the functions in the
with the

func loadLocations() {
for place in realm.objects(Place) {
let userLocationCoordinates = CLLocationCoordinate2DMake(place.latitude, place.longitude)
let pinForUserLocation = CustomAnnotation()
pinForUserLocation.coordinate = userLocationCoordinates
pinForUserLocation.title =
pinForUserLocation.subtitle = place.placeDescription = place
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 = sender!.title
vc.descriptionText = sender!.subtitle
vc.coordinate = sender!.coordinate = sender!.place

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download