Swift获取自定义注释信息

时间:2019-07-24 08:26:19

标签: swift

我正在尝试在注释didSelect函数中为对象提供一个视图控制器。但是当我尝试在新显示的viewcontroller中打印post.id时,它返回nil。如果我在post.id函数中打印addAnnotation,它将返回正常状态。

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

1 个答案:

答案 0 :(得分:1)

“ MKAnnotation”类型的值没有成员“ post”。您必须将MKPointAnnotation子类化

    class MyAnno: MKPointAnnotation {

    var post: Post? = nil

}

在功能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 }

像这样

相关问题