如何在’didSelectRowAtIndexPath’中访问segue – Swift / IOS

栏目: Swift · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/29974864/how-to-access-segue-in-didselectrowatindexpath-swift-ios
我知道如何使用prepareForSegue函数中的segue传递数据,但是我有一个TableViewCell,它有两个可能的段到两个不同的ViewControllers(我们现在就说A,B).建议 here

最好将segue连接到View控制器而不是tableCell本身,这实际上是完美的.但是我想在单击单元格时将信息传递给第二个View控制器,那么如何访问我连接到Source ViewController的segue.

码:

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

再说一遍:这个问题不是关于通过prepareForSegue传递信息

您应该使用didSelectRowAtIndexPath方法来确定是否选择了单元格.

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

然后在prepareForSegue方法中

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

解释…

>我使用索引路径作为发送方,因此我可以轻松地传递索引路径.您还可以使用其他UITableView方法检查当前选定的单元格,但我总是以这种方式成功完成

>你不能将performSegueWithIdentifier放在准备segue方法中,因为performSegueWithIdentifier会导致prepareForSegue;你只是四处走动,没有目标. (当你想执行segue时,总是会执行prepareForSegue)

>选择行时,prepareForSegue不会自行运行.这是您需要didSelectRowAtIndexPath的地方.你需要在前面描述的方法之外的performSegueWithIdentifier,它应该在didSelectRowAtIndexPath中

翻译自:https://stackoverflow.com/questions/29974864/how-to-access-segue-in-didselectrowatindexpath-swift-ios


以上所述就是小编给大家介绍的《如何在’didSelectRowAtIndexPath’中访问segue – Swift / IOS》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Ajax开发精要

Ajax开发精要

柯自聪 / 电子工业出版社 / 2006 / 45.00

书籍目录: 概念篇 第1章 Ajax介绍 2 1.1 Ajax的由来 2 1.2 Ajax的定义 3 1.3 Web应用程序的解决方案 5 1.4 Ajax的工作方式 7 1.5 小结 8 第2章 B/S请求响应机制与Web开发模式 9 2.1 HTTP请求响应模型 9 2.2 B/S架构的请求响应机......一起来看看 《Ajax开发精要》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具