【发布时间】:2016-06-15 13:34:21
【问题描述】:
我有一个 Realm 对象 Place,其中包含名称、描述和坐标对象。当 mapView 被加载时,会为 Realm 对象的每个实例创建一个 pin。我想要实现的是,当您单击每个引脚的注释时,您将进入详细视图,为您提供有关该地点的更多信息。有没有办法将此 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
}
}
【问题讨论】:
标签: ios swift annotations