我有一个带有名称,描述和坐标对象的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
}
}
答案 0 :(得分:1)
按view.annotation
访问注释并将其投放到
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
let annotation = view.annotation as! CustomAnnotation
performSegueWithIdentifier("showPlaceDetailSegue", sender: annotation)
}