ios - 在 Controller 之间传递变量 - Swift4

标签 ios swift tableview segue uistoryboardsegue

我正在尝试将 1 个变量传递给另一个 View Controller ,然后再传递给另一个 View Controller 。

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

map VC

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


结果

我不断得到

enter image description here

关于我做错了什么的任何提示?

最佳答案

如果通过导航按钮调用 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
    }*/

  }
}

关于ios - 在 Controller 之间传递变量 - Swift4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53176318/

相关文章:

ios - 在单独的类中使用 func() 需要拥有该方法的类的实例

ios - 使用仪器解决低内存警告

ios - 如果文本高度太大,则标签不显示

ios - 我的代码有什么问题。我正在尝试为表格 View Controller 着色

ios - 在 SwiftUI/Swift/Objective-C/Xamarin 中将底部边框线添加到 UI TextField View

ios - 如何使用 Xcode 自动完成枚举开关?

ios - tableView 显示重复值

arrays - 将 uiTableView 中的选定字符串从 Array 传递到新 ViewController 中的 uiLabel

titanium - 在 tableviewrow 钛合金中获取事件点击

ios - 从外部完成 block 检索变量 Parse Swift