So I'm trying to pass data from a cell to a different view controller, and while I do get back the value inside "user3" when I try to transport it over to "user2" I don't get any value. I have tried to print user2 and didn't get back anything and neither any errors. I'm suspecting it has something to do with the "func prepare" but I can't figure out what.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier:"searchCell", for: indexPath)
as! CustomTableViewCell
cell.titleField?.text = posts[indexPath.row].caption
cell.userUID?.text = posts[indexPath.row].uid
cell.descriptionField?.text = posts[indexPath.row].description
cell.tagsField?.text = posts[indexPath.row].tags
let photoUrl = posts[indexPath.row].photoUrl
let url = URL(string: photoUrl)
cell.SearchImage.sd_setImage(with: url, placeholderImage: nil)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = tableView.indexPathForSelectedRow
let currentCell = tableView.cellForRow(at: indexPath!)! as! CustomTableViewCell
let currentItem = currentCell.userUID!.text
var user3: String = ""
user3.append(currentItem!)
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationViewController = segue.destination as? userViewController {
destinationViewController.user2 = user3
}
}
}
I recommend to forget didSelectRowAt
and connect the segue to the prototype cell in Interface Builder rather than to the view controller.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = tableView.indexPathForSelectedRow
let currentCell = tableView.cellForRow(at: indexPath!)! as! CustomTableViewCell
let currentItem = currentCell.userUID!.text
var user3: String = ""
user3.append(currentItem!)
}
Then prepare(for segue
is called passing the table view cell in the sender parameter
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationViewController = segue.destination as? userViewController,
let cell = sender as? CustomTableViewCell,
let indexPath = tableView.indexPath(for: cell) {
let currentUID = posts[indexPath.row].uid
destinationViewController.user2 = currentUID
}
}
}
Get always the data from the model (the data source array), not from the view (the cell)