【问题标题】:Pass annotation title to embedded containerview when selected Swift选择 Swift 时将注释标题传递给嵌入式容器视图
【发布时间】:2019-05-29 07:47:15
【问题描述】:

我尝试使用 func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) 将注释标题传递给嵌入式容器视图。但是,当我构建并运行时,它不起作用。

我做错了什么?这是正确的方法吗?

我试过 func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) 查看代码

var annotationTitle = "Default"



func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView){
    if let annotation = view.annotation {
        annotationTitle = annotation.title!!
    }

}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showMapContainer" {
        let destination = segue.destination as! MapDetailContainerViewController
        destination.selectedAnnotation = annotationTitle as String
    }
}

}

数据作为“Deafult”而不是 annotation.title 值传递给 containerviewcontroller

【问题讨论】:

  • 感谢您的洞察力。容器和地图同时显示。我希望能够单击各种地图图钉并让容器显示有关当前选择的图钉的信息。

标签: swift xcode mkannotationview


【解决方案1】:

你说:

容器和地图同时显示。

如果它们同时被创建,那么prepare(for:sender:) 无疑会在didSelect 之前被调用。您可以通过一些断点或明智的print 语句来确认这一点。

所以你可以让prepare(for:sender:) 在某个局部变量中保存对segue.destination as? MapDetailContainerViewController 的引用,然后didSelect 可以设置selectedAnnotation

var embeddedViewController: MapDetailContainerViewController?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showMapContainer" {
        embeddedViewController = segue.destination as? MapDetailContainerViewController
    }
}

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let annotation = view.annotation,
        let title = annotation.title {
            embeddedViewController?.selectedAnnotation = title
    }
}

或者您可以绕过prepare(for:sender),直接使用children(以前称为childViewControllers):

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView){
    if let embeddedViewController = children.first as? MapDetailContainerViewController,
        let annotation = view.annotation,
        let title = annotation.title {
            embeddedViewController.selectedAnnotation = title
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 2018-07-31
    • 1970-01-01
    相关资源
    最近更新 更多