Home > database >  indexPath is nil after didSelectRow in tableView
indexPath is nil after didSelectRow in tableView

Time:02-10

I want to pass the selected row to the next VC. But it is always nil, no matter which row was clicked. I'm happy for any hints.

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

        self.performSegue(withIdentifier: "goToDetails", sender: self)
        
        
    }
    
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goTo Details" {
            if let indexPath = collectionTableView.indexPathForSelectedRow{
            let destinationVC = segue.destination as! DetailsViewController
                destinationVC.IdentifierAlbum = dataArray[indexPath.row].album
                destinationVC.IdentifierArtist = dataArray[indexPath.row].artist
                destinationVC.IdentifierRow = indexPath.row
                print (indexPath.row)
            }

CodePudding user response:

Instead of self you could pass the index path

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.performSegue(withIdentifier: "goToDetails", sender: indexPath) 
}

and get it in prepare(for, by the way the identifier doesn't match the identifier of performSegue, check it also in the storyboard

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToDetails",
       let indexPath = sender as? IndexPath { ...

But if the segue is connected from table view cell to the destination controller rather than from the view controller you can delete didSelectRow and the sender parameter contains the instance of the selected cell

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToDetails", 
       let cell = sender as? UITableViewCell,
       let indexPath = collectionTableView.indexPath(for: cell) { ...

CodePudding user response:

Use your IndexPath as your sender

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

    self.performSegue(withIdentifier: "goTo Details", sender: indexPath)

}

then on your prepare(for segue:) get the index path as follows

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goTo Details",
       let destinationVC = segue.destination as? DetailsViewController,
       let indexPath = sender as? IndexPath {

        //Whatever you do with indexPath

    }
}
  • Related