在控制器之间传递变量-Swift4

时间:2018-11-06 16:46:22

标签: ios swift tableview segue uistoryboardsegue

我正在尝试将1个变量传递给另一个视图控制器,然后再传递给另一个视图控制器。

var selectedPlace = Place {
    name = Daniel Webster Highway;
    country = United States;
    lat = 42.72073329999999;
    lon = -71.44301460000001;
} 

enter image description here

在单元格上选择时,我可以访问变量selectedPlace

我想将其传递给我的PlaceDetailVC以及MapVC。

由于某些原因,我无法实现这一目标。

PlacesVC

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let destinationVC = segue.destination as! PlaceDetailVC
    if let indexPath = tableView.indexPathForSelectedRow {
        destinationVC.selectedPlace = (places?[indexPath.row])!
        destinationVC.selectedTrip = selectedTrip!
    }

}

PlaceDetailVC

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "toMap" {
        let destinationVC = segue.destination as! MapVC
        if let indexPath = placesTable.indexPathForSelectedRow {
            destinationVC.selectedPlace = selectedPlace
        }
    }
}

我也尝试

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destinationVC = segue.destination as! MapVC
    if let indexPath = placesTable.indexPathForSelectedRow {
        destinationVC.selectedPlace = selectedPlace
    }
}

MapVC

print(selectedPlace,"<<<<<<")


结果

我不断得到

enter image description here

任何提示我做错了什么?

1 个答案:

答案 0 :(得分:3)

如果导航按钮调用了segue“ toMap”,则无需检查indexPath

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

if segue.identifier == "toMap" {
    let destinationVC = segue.destination as! MapVC
    destinationVC.selectedPlace = selectedPlace

    /*
    if let indexPath = placesTable.indexPathForSelectedRow {
        destinationVC.selectedPlace = selectedPlace
    }*/

  }
}