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

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

内容简介:翻译自: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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Artificial Intelligence

Artificial Intelligence

Stuart Russell、Peter Norvig / Pearson / 2009-12-11 / USD 195.00

The long-anticipated revision of this #1 selling book offers the most comprehensive, state of the art introduction to the theory and practice of artificial intelligence for modern applications. Intell......一起来看看 《Artificial Intelligence》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码