将对象传递给自定义注释视图

时间:2016-06-15 13:34:21

标签: ios swift annotations

我有一个带有名称,描述和坐标对象的Realm对象Place。加载mapView时,会为Realm对象的每个实例创建一个引脚。我想要实现的是,当您单击每个图钉的注释时,您将进入详细视图,为您提供有关该场所的更多信息。有没有办法将此Place对象传递给自定义注释,以便我可以在prepareForSegue函数中使用其属性,并在DetailViewController中访问和操作它们?

这是我的CustomAnnotation课程:

import Foundation
import UIKit
import MapKit
import RealmSwift

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

此处ViewController中的函数与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
        }
    }

1 个答案:

答案 0 :(得分:1)

view.annotation访问注释并将其投放到

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