Ahmed Al Abdulaal
Ahmed Al Abdulaal

Reputation: 280

Failing to pass data between VC

I have two VC's and I'm trying to pass data from the first VC to the second using a segue. The first VC has a tableview each cell contains a title and a description labels that are stored using core data. I want to have a detail view of each cell in the second VC. I have initialized two strings to store the values from the first VC and assigned them to strings in the second VC.

Please take a look at the code below:

var SelectedTitle = String()
var SelectedDisc = String()

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    SelectedTitle = self.listAthkar[indexPath.row].title!
    print(SelectedTitle)
    SelectedDisc = self.listAthkar[indexPath.row].details!
    print(SelectedDisc)
    performSegue(withIdentifier: "showCell", sender: self)
}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "showCell") {
        var destinationVC = segue.destination as! showCellVC
        destinationVC.passedTittle = SelectedTitle
        destinationVC.passedDisc = SelectedDisc
    }
}


class showCellVC: UIViewController {

var passedTittle = String()
var passedDisc = String()
@IBOutlet weak var cellTitle: UILabel!
@IBOutlet weak var cellDisc: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()
    cellTitle.text = passedTittle
    cellDisc.text = passedDisc
    print("Title Passed is \(passedTittle)")
    print("Discription Passed is \(passedDisc)")
}

When I test the app the console prints:

Title Passed is 
Discription Passed is 
title
Description

Here is a picture of the actual cell

Cell picture Any idea why it's failing to pass the data to the second VC?

Upvotes: 0

Views: 69

Answers (2)

Paulw11
Paulw11

Reputation: 115051

It looks like you have put an action segue on your tableview cell in your storyboard. Since you are using a programmatic segue you don't want this. The action segue is firing before your didSelect method, so the segue is occurring before the variables are set.

Upvotes: 3

Bhupat Bheda
Bhupat Bheda

Reputation: 1978

Try like this! Make separate Array for "Title" and "Description"

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

    self.performSegue(withIdentifier: "showCell", sender: indexPath)
}

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

   if (segue.identifier == "showCell") {
    var destinationVC = segue.destination as! showCellVC
    destinationVC.passedTittle = self.listAthkar[(sender as! IndexPath).row]
    destinationVC.passedDisc = self.listAthkar[(sender as! IndexPath).row]
   }
}

Upvotes: 0

Related Questions