在 Swift 中通过 segue 传递多个变量

Pass multiple variables through segue in Swift

我看过很多教程,其中人们通过 segue 将单个变量传递到单独的视图控制器。但是我如何将整个结构或 class 信息发送到单独的 segue?然后在另一边打开它?示例:在 table 视图中,我单击一个玩家的名字,它会继续显示另一个视图控制器中的详细信息?

示例:棒球阵容...

class Player {
    var playerName: String = ""
    var playerPosition: String = ""
    var playerImage: UIImage = ""
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedPlayer = player[indexPath.row].playerName

    performSegue(withIdentifier: "player", sender: selectedPlayer)
}

您需要使用prepare函数:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "player" {
        if let player = sender as? Player {
            let secondViewController = segue.destination as! SecondViewController
            secondViewController.player = player
        }
    }
}

调用performSegue时将调用此函数。在 secondViewController 中声明一个播放器变量,您只需在 prepare 函数中传递该变量。

并且在您的 didSelectRowAt 更改中:

let selectedPlayer = player[indexPath.row].playerName

收件人:

let selectedPlayer = player[indexPath.row]

因此您传递了整个 Player 对象,而不仅仅是 playerName.