首页 > 解决方案 > 为返回做准备

问题描述

所以我试图在 Swift 中实现的代码是基于这里的答案,用于从 ViewController 传回数据: Passing Data with a Callback

现在我的问题是在我打电话之后:

self.navigationController?.popViewController(animated: true)

在我原来的视图控制器中没有调用 Prepare For Segue 函数。我认为无论如何都不应该调用它,但是从那个答案中我认为有一种可能的方法吗?


第一个视图控制器片段

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    //ignore this segue identifier here, this function works when I am showing a new VC
    if(segue.identifier == "certSegue"){
        let certVC = segue.destination as! CertificateViewController
        certVC.profileModel = profileModel
    }

    //this is what I need to be called
    if(segue.identifier == "dpSegue"){
        print("dpSegue")
        let dpVC = segue.destination as! DatePickerViewController
        dpVC.callback = { result in
            print(result)
            print("Data")
            // do something with the result
        }
        //dpVC.dailyBudgetPassedThrough = "Test"
    }
}

 func showDatePicker(){
    let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "DatePickerVC") as? DatePickerViewController
    self.navigationController?.pushViewController(vc!, animated: true)

}

第二个视图控制器

import UIKit

class DatePickerViewController: UIViewController {

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

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

func sendBackUpdate(){

   print("Callback")
    callback?("Test")
}

@IBAction func cancelButton(_ sender: Any) {
    self.navigationController?.popViewController(animated: true)
}

@IBAction func updateButton(_ sender: Any) {
    sendBackUpdate()
    self.navigationController?.popViewController(animated: true)
}


}

标签: swiftxcodecallback

解决方案


prepareForSegue如果在 Interface Builder 中连接了 segue,则调用

  • 从表/集合视图单元格到目标视图控制器,然后点击该单元格。
  • 从源视图控制器到目标视图控制器,并performSegue(withIdentifier:sender:)在源视图控制器中调用。

当要呈现视图控制器时不会调用它pushViewController

在您的情况下showDatePickerprepare(for segue不需要在实例化控制器后分配回调。

func showDatePicker(){
    let vc = UIStoryboard(name: "Main", bundle: .main).instantiateViewController(withIdentifier: "DatePickerVC") as! DatePickerViewController
    vc.callback = { result in
        print(result)
        print("Data")
        // do something with the result
    }

    self.navigationController?.pushViewController(vc, animated: true)
}

推荐阅读