我试图在注释 didSelect
函数中呈现一个带有对象的 View Controller 。但是当我尝试在新呈现的 View Controller 中打印 post.id
时,它返回 nil。如果我在 addAnnotation
函数中打印 post.id
,它会正常返回。
func addAnnotations(post: Post, title: String?, locationName: String?, coords: [CLLocation]) {
for coord in coords {
let CLLCoordType = CLLocationCoordinate2D(latitude: coord.coordinate.latitude,
longitude: coord.coordinate.longitude);
let anno = MKPointAnnotation()
anno.coordinate = CLLCoordType
if title == "" {
anno.title = locationName
} else {
anno.title = title
}
mapView.addAnnotation(anno)
}
}
let activityPreview = ActivityPreviewLauncher()
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
//Returns an error
guard let post = view.annotation?.post else { return }
activityPreview.showActivityPreview()
activityPreview.homeController = self
activityPreview.post = post
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation{
return nil
} else{
let pinIdent = "Pin"
var pinView: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: pinIdent) as? MKPinAnnotationView {
dequeuedView.annotation = annotation
pinView = dequeuedView
} else {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: pinIdent)
}
return pinView
}
}
最佳答案
“MKAnnotation”类型的值没有成员“post”。你必须继承 MKPointAnnotation
class MyAnno: MKPointAnnotation {
var post: Post? = nil
}
在 func addAnnotations
中覆盖你的代码
let CLLCoordType = CLLocationCoordinate2D(latitude: coord.coordinate.latitude,
longitude: coord.coordinate.longitude);
let anno = MyAnno()
anno.coordinate = CLLCoordType
anno.post = post
if title == "" {
anno.title = locationName
} else {
anno.title = title
}
mapView.addAnnotation(anno)
然后在 didSelect
中检查注释类型
guard
let anno = view.annotation as? MyAnno,
let post = anno.post
else { return }
像这样
关于Swift 获取自定义注解信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57178461/