Swift 3.0 使用 Segue 在视图控制器之间传递信息

Swift 3.0 Using Segue to Pass Information Between View Controllers

我正在尝试将文本值从一个 VC(称为第二个 VC)传递到另一个 VC(第一个 VC)。第二个VC 中的信息将决定第一个VC 中文本字段的文本值。我曾尝试使用文档来解决这个问题,但我一定是感到非常困惑,或者出现了其他问题 - 我无法弄清楚是哪个。

我的第二个VC:

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if(segue.identifier == "saveSegue") {

        let destinationVC = segue.destination as! firstVC

        destinationVC.addressTextField.text = searchBar.text
    }
}


@IBAction func savePressed(_ sender: Any) {


    performSegue(withIdentifier: "saveSegue", sender: self)
}

回到第一个 VC 后,textField 未按预期填充 searchBar 文本。 (searchBar 文本不为零)据我了解,当在第二个 VC 中选择按钮并调用 performSegue 时,它​​还会调用 prepareForSegue 并在返回时设置 addressTextField.text 值第一个VC。我不确定我的逻辑是否正确。

在你的 FirstViewController 中

    @IBAction func dismissSearchVC(_ sender: UIStoryboardSegue) {
      let sourceVC = sender.source as! viewController2
      addressTextField.text = sourceVC.searchBar.text
}

在你的第二个ViewController中

var searchedText = ""


@IBAction func savePressed(_ sender: Any) {
    performSegue(withIdentifier: "saveSegue", sender: self)
}

现在连接你的 viewController 以在顶部退出并添加一个标识符到该 segue 作为 saveSegue 和 select dismissSearchVC 从下拉列表

然后 select 你从这里继续

现在 select "unwind segue to DismissSearchVC" 并在属性检查器中添加标识符..

我怀疑您从一个视图控制器到另一个视图控制器的转换不是因为 segue 而发生的,而是因为按钮的连接而发生的。

删除从 UIButton 连接到 AnotherViewControllersegue

现在从包含 ViewController 的按钮添加一个 segueAnotherViewController。 (不是从 UIButtonAnotherViewController,而是从 ViewControllerAnotherViewController)。并给那个 segue 你期望的标识符。