Search code examples
iosiphoneuitableviewswift3uistoryboardsegue

Passing value from table view controller to view controller


I tried to pass the value of the cell that the user clicks on to another view controller.

Here is my code.

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    productDisplayed = currentProductList[indexPath.row] as? Product
    performSegue(withIdentifier: "ProductDetailSegue", sender: self)
}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if ( segue.identifier == "AddProductSegue"){
        let controller: AddProductViewController = segue.destination as! AddProductViewController
        controller.delegate = self
    }

    if ( segue.identifier == "ProductDetailSegue"){

        let controller: ProductDetailsViewController = segue.destination as! ProductDetailsViewController
        controller.currentProduct = productDisplayed
    }
}

Firstly, I didn’t write “performSegue()”. The issue I met is that the screen will be transferred firstly rather than assign the value to “productDisplayed”, which means the object “currentProduct” in the second VC is nil.

Then I added “performSegue()”. It still didn’t work. The thing is the second screen was displayed twice. The first time is same with the picture above. And the second time is correct.

But when I tried to click the back button on the left top. It returned to the nil page rather than the ProductDetail page. The screenshot is as follows.

enter image description here

enter image description here

It seems like "prepare" method always being called first then the tableView. How to change the order? If can, this should be fixed I think.

Hope to get your help. Thank you.


Solution

  • Cause of Problem:
    In your storyboard, you may have bound, ProductDetailsViewController with UITableViewCell directly.

    It means, upon click/selection of row, it will perform segue (navigation) operation directly.

    At the same time, programatically you perform navigation operation using performSegue(withIdentifier: "ProductDetailSegue", sender: self)

    Solution:
    You have two ways to solve this issue.

    1. I recommend - In your story board, switch segue connection from UITableViewCell to UIViewController (Remove segue connection from UITableViewCell and attach the same segue connection with UIViewController of your tableview)
    2. In your source code, delete/remove this line performSegue(withIdentifier: "ProductDetailSegue", sender: self) and handle data transmission from this function override func prepare(for segue: UIStoryboardSegue, sender: Any?)