在 swift 4 中使用通过 performSegue 打开的关闭页面时如何在视图控制器和 TableViewController 之间传递数据?

how pass data between view controller and TableViewController when using dismiss page that opened with performSegue in swift 4?

我在这里使用这段代码将数据从第一个视图控制器传递到第二个视图控制器

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? secondViewController {
        vc.showPageType = self.checkEdit
   }

但问题是,在第二个视图控制器中,我有文本字段,当用户填写该文本字段并按下按钮提交时,secondViewController 将使用此方法关闭

dismiss(animated: false, completion: nil)

现在我不能使用 perform segue 方法将文本字段文本传递给第一个视图控制器我如何在 swift4 中做到这一点?

添加到您的 secondViewController 源代码文件:

protocol SecondViewControllerDelegate {

    func submitButtonPushedWithText(_ text: String)
}

添加到class secondViewController 属性:

var delegate: SecondViewControllerDelegate?

然后让你的第一个控制器符合 SecondViewControllerDelegate 并实现方法 submitButtonPushedWithText(:):

class FirstViewController: UIViewController, SecondViewControllerDelegate {

    func submitButtonPushedWithText(_ text: String) {
        // use text from textField of second controller 
    }
}

在呈现之前还要设置第二个控制器的委托 属性:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? secondViewController {
    vc.showPageType = self.checkEdit
    // setup delegate
    vc.delegate = self
}

现在您可以在调用 dismiss(animated: false, completion: nil) 之前在第二个控制器中调用方法 submitButtonPushedWithText(_ text: String):

func submitButtonPushed() {
    delegate?.submitButtonPushedWithText(textField.text!)
    dismiss(animated: false, completion: nil)
}