How to access segue in 'didSelectRowAtIndexPath' - Swift / IOS

I know how to transfer data using segues from the prepareForSegue function, but I have a TableViewCell from which there are two possible transitions to two different ViewControllers (let them just say A, B at the moment). It has been suggested here that it is best to connect segues to the View controller, and not to the TableCell itself, which worked effectively. But I want to pass information to the second View controller when the cell is clicked. So how to access the segue that I connected to the Source ViewController.

code:

Inside prepareForSegue

if segue.identifier == "showQuestionnaire"{ if let indexPath = self.tableView.indexPathForSelectedRow() { let controller = (segue.destinationViewController as! UINavigationController).topViewController as! QuestionnaireController let patientQuestionnaire = patientQuestionnaires[indexPath.row] as! PatientQuestionnaire controller.selectedQuestionnaire = patientQuestionnaire self.performSegueWithIdentifier("showQuestionnaire", sender: self) } } 

Again: this question is not about passing information through prepareForSegue

+6
source share
1 answer

You must use the didSelectRowAtIndexPath method to determine if a cell has been selected.

 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("showQuestionnaire", sender: indexPath); } 

Then in your prepareForSegue method

 override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if (segue.identifier == "showQuestionnaire") { let controller = (segue.destinationViewController as! UINavigationController).topViewController as! QuestionnaireController let row = (sender as! NSIndexPath).row; //we know that sender is an NSIndexPath here. let patientQuestionnaire = patientQuestionnaires[row] as! PatientQuestionnaire controller.selectedQuestionnaire = patientQuestionnaire } } 

To explain ...

  • I used the index path as the sender, so I can easily go through the index path. You can also check the selected cell using other UITableView methods, but I always did this with success.
  • You cannot put performSegueWithIdentifier in the preparation method for the segue method, because performSegueWithIdentifier leads to prepareForSegue ; You just loop around and without purpose. (When you want to execute segue, prepareForSegue is always executed)
  • prepareForSegue does not start by itself when a row is selected. Here you need didSelectRowAtIndexPath . You need to performSegueWithIdentifier outside the method, as described above, which should be in didSelectRowAtIndexPath
+23
source

Source: https://habr.com/ru/post/986319/


All Articles