gpt4 book ai didi

ios - 将对象传递给自定义注释 View

转载 作者:行者123 更新时间:2023-11-29 00:53:41 25 4
gpt4 key购买 nike

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

这是我的 CustomAnnotation 类:

import Foundation
import UIKit
import MapKit
import RealmSwift

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

这里是 ViewControllermapView 的函数:

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
}
}

最佳答案

通过view.annotation访问注释并将其转换为您的自定义类

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

关于ios - 将对象传递给自定义注释 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37837034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com