swifttableviewseguedidselectrowatindexpath

How to perform segue from tableview cells to different view controllers


I want to perform segue from tableview cells to different view controllers, not by using the same controller and changing things in it. I have two section as it is seen in the image.

I did it like this but it didn't work. When both sections are clicked, the same page is displayed:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.row == 0 {
        performSegue(withIdentifier: "toSettings1", sender: nil)
    } else if indexPath.row == 1 {
        performSegue(withIdentifier: "toSettings2", sender: nil)
    }
    
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toSettings1" {
        let vc = segue.destination as? ReferencesViewController
    } else if segue.identifier == "toSettings2" {
        let vc = segue.destination as? LiabilityViewController
    }
}

Solution

  • You have 2 sections and 1 row for each one you should write it as below:

    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            
            if indexPath.row == 0 && indexPath.section == 0 {
                
                performSegue(withIdentifier: "toSettings1", sender: nil)
            }else if indexPath.row == 0 && indexPath.section == 1 {
                performSegue(withIdentifier: "toSettings2", sender: nil)
            }
            
        }
        
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            
            if segue.identifier == "toSettings1" {
                let vc = segue.destination as? ReferencesViewController
            }else if segue.identifier == "toSettings2"{
                let vc = segue.destination as? LiabilityViewController
            }
        }```