Passing a value from a table view controller to a view controller

I tried to pass the value of the cell the user clicks 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
    }
}

      

First, I didn't write "performSegue ()". The problem I am facing is that the screen will be cast first and not assigned the value "productDisplayed", which means the "currentProduct" object in the second VC is null.

Then I added "performSegue ()". It still didn't work. The point is that the second screen was displayed twice. The first time is the same as the picture above. And the second time is correct.

But when I tried to click the back button at the top left. It returned to the nil page, not the ProductDetail page. The screenshot looks like this.

enter image description here

enter image description here

It seems that the "prepare" method is always called first and then the tableView. How to change an order? If possible this should be fixed I think.

Hope to get your help. Thank.

+3


source to share


1 answer


Reason for the problem:
In your storyboard, you can directly link ProductDetailsViewController

to UITableViewCell

.

This means that after the row is clicked / selected, it will perform the segue (navigation) operation directly.

At the same time, programmatically you navigate with performSegue(withIdentifier: "ProductDetailSegue", sender: self)



Solution:
You have two ways to solve this problem.

  • I recommend - In your storyboard, switch the SEGUE connection from UITableViewCell

    to UIViewController

    (Remove the SEGUE connection from UITableViewCell

    and attach the same SEGUE connection from UIViewController

    your Tableview)
  • In your source code, remove / remove this line performSegue(withIdentifier: "ProductDetailSegue", sender: self)

    and handle the data transfer from this functionoverride func prepare(for segue: UIStoryboardSegue, sender: Any?)

+1


source







All Articles