准备退还Segue

时间:2019-03-29 17:03:33

标签: swift xcode callback

因此,我要在Swift中实现的代码基于此处的答案,用于将数据从ViewController传回: Passing Data with a Callback

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

self.navigationController?.popViewController(animated: true)

我的原始View Controller中未调用“准备缝合”功能。我认为无论如何都不应调用它,但是从该答案中我认为有可能这样做吗?


第一视图控制器摘要

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)
}


}

1 个答案:

答案 0 :(得分:0)

如果在Interface Builder中连接了Segue,则会调用

prepareForSegue

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

当视图控制器将与pushViewController一起出现时,不会被调用

在您的情况下,在showDatePicker中实例化控制器后分配回调,则不需要prepare(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)
}