Home > Mobile >  Send other data from UITableView to ViewController
Send other data from UITableView to ViewController

Time:07-26

I have a Decodable Proto which holds data.

The Name is displayed on a label in the UITableViewCell but the message isn't but needs to be transferred with the Name.

A message gets displayed, but it`s the one of the previous cell. If I close the DetailView and click the cell again, the right message is displayed.

struct Response: Decodable {
                    let array: [Content]

                    struct Content: Decodable {

                        let Name: String
                        let Message: String
                    }
                }

    var responseDec: Response?

That's the didSelectRow and prepare func


var username = ""
var message = ""

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

         let res = self.responseDec?.array[indexPath.row]

          index = indexPath.row

          username = res?.Name ?? "N/A"
          message = res?.Message ?? "N/A"

          let cell = tableView.cellForRow(at: indexPath) as? Cell

         performSegue(withIdentifier: "goToVC", sender: cell)

    }

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "goToVC" {

            let cell = sender as? Cell

            let vc = segue.destination as! ViewController


             vc.name = cell?.nameLabel.text ?? "N/A"
             vc.message = message

          }
}

CodePudding user response:

You can try to grab the data for selected index path by creating a global variable. Try this

 var selectedIndexPath: IndexPath?

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

     selectedIndexPath = indexPath
     performSegue(withIdentifier: "goToVC", sender: self)

}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "goToVC" {

      if let indexpath = selectedIndexPath, let vc = segue.destination as? ViewController{
           let res = self.responseDec?.array[indexpath.row]
           vc.name = res?.Name ?? "N/A"
           vc.message = res?.Message ?? "N/A"

      }}}

CodePudding user response:

I think you should use present or push to show your view controller. And check your data with a break point.

Or if you wanna keep use segue;

  • Keep segue identifier as a constant
  • Use guard let casting a cell
  • Create a struct that includes name and message
  • Give the model to performSegue as the sender and catch it with guard let in the prepare function
  • Related