Logan Cohen
Logan Cohen

Reputation: 25

How do I use a table view to go to different view controllers?

I have a tableview with one prototype cell. I can get multiple cells to appear with the proper content whenI run the app. I want each cell to navigate to a different view controller, rather than the same view controller simply displaying different content. I created a segue to each view controller and named it accordingly. But I cannot figure out what to do next. Do I use the below with some sort of if function?:

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

How do I specify that if the first cell is selected to use segue "one" to go to view controller "one" and if cell two is selected use segue "two" to go to view controller "two"? I know this is harder without code, but conceptually how does this work?

Upvotes: 1

Views: 1822

Answers (2)

Abshalom Salama
Abshalom Salama

Reputation: 3

You can give identifier to your story board vc from Xcode identity inspector bar,Preferably using the same name as your UIViewController name

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        
        let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "MyViewController") as? MyViewController
        self.navigationController?.pushViewController(vc!, animated: true)
        
    }

Upvotes: 0

Nayan Dave
Nayan Dave

Reputation: 1680

Yes, didSelectRowAt function is the best way to identify which cell or row is selected at the time.

  • didSelectRowAt Function should be like below

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {
           performSegue(withIdentifier: "FirstViewController", sender: nil)
        } else if indexPath.row == 1 {
           performSegue(withIdentifier: "SecondViewController", sender: nil)
        }
    }
    
  • Segue Prepare Function Should be Like Below

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

Hope, It Helps :)

Upvotes: 2

Related Questions