1

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?

  • Does this answer your question? [How to segue programmatically in iOS using Swift](https://stackoverflow.com/questions/27604192/how-to-segue-programmatically-in-ios-using-swift) – CloudBalancing Jan 17 '22 at 03:19

2 Answers2

2

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

Nayan Dave
  • 1,078
  • 1
  • 8
  • 30
  • 1
    Or better yet, have an array of identifier strings, load the correct one based on the IndexPath of the selected item, and use that identifier to instantiate the destination view controller. – Duncan C Jan 17 '22 at 05:04
  • @DuncanC Yes, That's better and efficient!!, Here it was just an example for easy understanding.. – Nayan Dave Jan 17 '22 at 05:14
0

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