关闭我的视图控制器,但 "prepare" 下面的视图控制器

Dismiss my view controller but "prepare" the view controller underneath

我有一个模态呈现的 ViewController,里面有一个 UITableView。当用户单击“Days”时,它会显示此视图控制器(模态)。这是我的故事板:

我想要做的是,当我在模态中单击 table 视图中的一个单元格时,我想关闭模态,但还要在根视图控制器中加载新数据。

如何从 segued 视图控制器访问根视图控制器?

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.dismiss(animated: true, completion: nil)
}

// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destinationVC = segue.destination as! DayView
    if let indexPath = tableView.indexPathForSelectedRow {
        destinationVC.day = days![indexPath.row]
    }
}

我想要像我上面写的那样的东西,但是虽然我的模式确实被解雇了,但我想要的是以某种方式在单击 TableViewCell 时触发准备函数中的代码。

比protocol/delegate更短更简单的方法是创建闭包:

为了发回一个字符串,首先 ViewController:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let viewControllerB = segue.destination as? ViewControllerB {
        viewControllerB.callback = { message in
            
            //Do what you want in here!

        }
    }
}

在ViewController乙:


var callback : ((String) -> Void)?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    callback?("Your Data")
    self.dismiss(animated: true, completion: nil)
}

你走在正确的道路上,你需要再添加两个功能 1。 和一个不是目的地它的来源所以你需要从目的地更改为来源。

 // MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destinationVC = segue.source as! DayView
    if let indexPath = tableView.indexPathForSelectedRow {
        destinationVC.day = days![indexPath.row]
    }
}

供参考:How to Pass Data in an Unwind Segue