Search code examples
iosswiftuitableviewstoryboardsegue

Swift pass the value from main to another viewcontroller with storyboard segue


I am trying to implement when user click the tableView cell, that selected cell value need to pass detail viewcontroller. Here, the transition connection I made by storyboard (not programmatically) and present modally transition I used.

I would like to know how to do, so provide some example.

present modally transition

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

   // here I need implement get selected index path and passing values to another vc

} 

Solution

  • Use preparefor(segue:) as follows,

    I'm assuming few thing

    1. Your current view controller is showing a list of player.
    2. You are showing a list of player.
    3. Tapping a player you wanted to show the player details.
    4. Your player details view controller name is PlayerDetailsVC.
    5. You a array of Players model, which are you showing in the tableview.
    6. From storyboard, your tableview selection mode is single selection.

    Based on these assumption your code will be like following

     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let indexPath = tableView.indexPathForSelectedRow{
            let selectedRow = indexPath.row
            let PlayerDetailsVC= segue.destination as! DetailViewController
            let member = "\(players[selectedRow].name ?? "")"
            PlayerDetailsVC.player = member
        }
    }
    

    In DetailViewcontroller need to do below

    var player:String? //print it within viewdidload