如何在';didSelectRowAtIndexPath';-Swift/IOS
我知道如何使用segues fromprepareForSegue函数传递数据,但我有一个TableViewCell,其中有两个可能的segue到两个不同的ViewController(现在我们只说a,B)。有人建议最好将segues连接到View controller,而不是tableCell本身,因为tableCell实际上工作得很好。但是我想在单击单元格时将信息传递给第二个视图控制器,以便了解如何访问连接到源视图控制器的segue 代码: 内部准备室如何在';didSelectRowAtIndexPath';-Swift/IOS,ios,uitableview,swift,segue,Ios,Uitableview,Swift,Segue,我知道如何使用segues fromprepareForSegue函数传递数据,但我有一个TableViewCell,其中有两个可能的segue到两个不同的ViewController(现在我们只说a,B)。有人建议最好将segues连接到View controller,而不是tableCell本身,因为tableCell实际上工作得很好。但是我想在单击单元格时将信息传递给第二个视图控制器,以便了解如何访问连接到源视图控制器的segue 代码: 内部准备室 if segue.identifier
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)
}
}
同样:此问题与通过prepareforsgue传递信息无关。您应该使用
didSelectRowAtIndexPath
方法来确定是否选择了单元格
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("showQuestionnaire", sender: indexPath);
}
然后在prepareforsgue
方法中
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
}
}
解释
performsguewithidentifier
放入prepare for segue方法中,因为performsguewithidentifier
导致prepareforsgue
;你只是一圈又一圈,没有目标。(如果要执行序列,则始终执行prepareForSegue)prepareforsgue
在选择行时不会自行运行。这就是您需要的didSelectRowAtIndexPath
。如前所述,在方法之外需要一个performsguewithidentifier
,它应该位于didSelectRowAtIndexPath
我不明白这个问题,但如果问题是如何将数据发送到prepareForSegue,请使用performSegueWithIdentifierif([segue.destinationViewController isKindOfClass:[A_VC class]]){…}的sender字段,否则{…}在
prepareForSegue
中传递信息是正确的方法。但是,您绝对不应该在prepareforsgue
内调用performsguewithidentifier
。看起来您已经在使用let controller=segue.destination as…
行将信息传递给下一个视图控制器。你具体想做什么,而不是在该函数中做?正如其他地方提到的,不要在prepareforsgue
内调用performsguewithidentifier
。伙计们,我正在尝试设置控制器。SelectedQuestion在从didSelectRowAtIndexPath执行segue时,但在最后,它执行到我的目标控制器的segue,但它没有在其中设置SelectedQuestion值,我认为这是因为我无法访问连接到源代码视图控制器的segue来创建DestinationViewController,就像prepareforsgue函数一样。我希望这次我清楚了。我尝试了您的解决方案,但在第行let controller=(segue.destinationVIewController…
)上出现了此错误。无法将类型为“UIViewController”(0x105866418)的值强制转换为“CarePortal.QuestionnaireController”(0x1034f1850)。您可能将错误的对象类型设置为强制类型,您能检查并确保您强制类型的所有内容都是您所描述的吗?将as!更改为as?成功了。感谢@Nate。Swift对可选值越来越严格:@是的,请记住,将来,设备必须知道您要执行一个序列,以便它能够执行ows准备:)我有一个关于这个解决方案的问题。如果用户(意外)双击单元格,则会触发两次performSegue。如何确保它只触发一次?