所以我试图在Swift中实现的代码基于这里的答案,用于从ViewController传回数据:Passing Data with a Callback
现在我的问题是在我打电话之后:
self.navigationController?.popViewController(animated: true)
我的原始View Controller中未调用Prepare For Segue功能。我认为它不应该被调用但是从这个答案我认为有可能这样做吗?
First View Controller Snippets
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)
}
}
如果在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)
}