Xcode:将信息从UITableViewController传递到UIViewController

时间:2017-06-16 12:47:04

标签: ios swift xcode uitableview uiviewcontroller

我有一个UIViewController,它应该根据在UITableViewController中按下的Cell来显示DetailInformations。

目前我正在通过续集传递它们:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "show" {
            var ctrl = segue.destination as! DetailViewController
            ctrl.information = _informationList[id]
        }
    }

id变量通过以下方式设置:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        id = indexPath.row

    }

现在在我的UIViewController中,我用以下内容更改信息:

override func viewDidLoad() {
        super.viewDidLoad()
        setInformation(i: information)
    }

现在我的问题是,如果我按下,让我们说单元格2.它切换到ViewController并显示单元格1的信息。然后我回到tableview并按下单元格3.然后它显示单元格2。

简而言之,似乎在设置新信息之前加载了viewController(带有最后的信息)。

有没有更好的方法来解决这个问题?

2 个答案:

答案 0 :(得分:1)

尝试使用indexPathForSelectedRow中的prepareForSegue,因为您已经创建了从UITableViewCell到目标ViewController的segue,以便prepareForSegue之前会调用didSelectRowAt

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "show" {
        var ctrl = segue.destination as! DetailViewController
        if let indexPath = self.tableView.indexPathForSelectedRow {
            ctrl.information = _informationList[indexPath.row]
        }
    }
}

答案 1 :(得分:0)

我假设你所描述的是你在故事板中使用segue直接从单元格链接到详细视图控制器。如前所述,这不是您想要做的,因为您没有获得您期望的事件顺序。你可以使用委托设计模式,但假设你想坚持使用segues,你需要制作" show"从表VC本身到细节VC的segue。然后,您可以从tableView didSelectRowAt代码手动调用segue。

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    id = indexPath.row
    performSegue(withIdentifier: "show", sender: self)
}

最后,当您回来捕获详细VC中发起的任何数据更改时,您可以使用展开segue。