Swift 获取自定义注解信息

标签 swift

我试图在注释 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/

相关文章:

ios - UIApplicationOpenURLOptionsKey.sourceApplication 可以为零吗?

ios - 导航栏搜索结果

ios - CLGeoCoder 没有以正确的顺序附加地标

swift - 为什么我的值只在 swift 第一次打开和关闭应用程序后设置?

ios - 带有 GPS 数据的 imagePickerController (Swift)

swift - 意外发现 Nil SKSpriteNode

swift - 视频在 tvOS 中播放完后如何播放广告?

iOS-swift 如何制作带分页的表格 View ?

arrays - 如何根据其创建日期订购 PFObjects?

ios - swift 将阴影应用于导航栏