Search code examples
iosswifttableviewsegue

indexPath is nil after didSelectRow in tableView


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)
            }


Solution

  • 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) { ...