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

爷,独闯天下 提交于 2019-11-30 05:20:26

You should be using the didSelectRowAtIndexPath method to determine whether or not a cell was 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...

  1. I used the index path as the sender so I can easily pass the index path. You could also check for the currently selected cell using other UITableView methods, but I've always done it this way with success
  2. You can't put performSegueWithIdentifier within the prepare for segue method, because performSegueWithIdentifier leads to prepareForSegue; You are just looping around and around with no aim. (When you want to perform a segue, prepareForSegue is always executed)
  3. prepareForSegue doesn't run by itself when a row is selected. This is where you need didSelectRowAtIndexPath. You need a performSegueWithIdentifier outside of the method as described previously, which should be in didSelectRowAtIndexPath
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!