swift - 为返回做准备
问题描述
所以我试图在 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)
}
}
解决方案
prepareForSegue
如果在 Interface Builder 中连接了 segue,则调用
- 从表/集合视图单元格到目标视图控制器,然后点击该单元格。
- 从源视图控制器到目标视图控制器,并
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)
}
推荐阅读
- time - 时间范围面板在 Grafana 中不可用
- java - 如何解决有关变量的以下问题?
- node.js - 如何从节点js中的“then”中获取数据?
- javascript - 如何修复“node.decodeJpeg 不是函数”(tensorflow.js)?
- java - 如何模拟您使用 powermockito 监视的班级中的成员
- c - 了解 C 中的后增量概念
- python - PySide2 Qthread 崩溃
- c# - C# 输入字符串的格式不正确。使用 c# .net
- sql - 如何获取标签值并替换存储在表中的html代码中的标签
- angular - 如何使用 angular 和 typescript 从 .graphql 文件加载查询