Search code examples
iosswiftuitableviewsegue

passing data via segue using didSelectRowAt


I want to pass data via segue from UITableViewController to a ViewController. The problem is that the data I want to pass the indexPath.row value (i.e the row selected in the UITableView).

I have declared declared a variable var counter: Int?in the ViewController which is known as foodinfo. This is my code in the UITableView:

var rowselected: Int?

override func viewDidLoad() {
    super.viewDidLoad()

}

//what happens when row is selected
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    rowselected = indexPath.row

    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destinationVC = segue.destination as! foodinfo
        destinationVC.counter = rowselected
    }

    self.performSegue(withIdentifier: "dayx", sender: self)
    }

for some reason the counter in the ViewController has a value of nil. what am i doing wrong?


Solution

  • Your prepare for segue should not be in inside override func tableView( move it so its like this:

     override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    rowselected = indexPath.row
    self.performSegue(withIdentifier: "dayx", sender: self)
    
    }
    

    also should be override:

       override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
         if segue.identifier == "dayx" {
        let destinationVC = segue.destination as! foodinfo
        destinationVC.counter = rowselected
        }
    }
    

    because override func prepareForSegue method is called after self.performSegue. So now you can successfully set the value rowSelected = indexPath.row inside override func tableView( and when self.performSegue is called it will correctly pass the data as set in the override func prepareForSegue