ios - Swift - 将数据从子视图传递到父视图
问题描述
我想将我的数据从子视图控制器传递到父视图控制器。
我只是将子视图移动到父视图的顶部,这是我的代码:
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let toChildView = storyBoard.instantiateViewController(identifier: "toChildView")
// show child view
self.addChild(toChildView)
toChildView.willMove(toParent: self)
toChildView.view.frame = self.view.bounds
self.view.addSubview(toChildView.view)
toChildView.didMove(toParent: self)
这是代表:
protocol DataDelegate {
func printTextField(string: String)
}
我将变量委托添加到我的子视图
var delegate: DataDelegate?
并将数据发送到父视图
@IBAction func btnSend(_ sender: Any) {
delegate?.printTextField(string: textField.text)
}
并关闭子视图,例如:
@IBAction func btnClose(_ sender: Any) {
// back to parent view
self.willMove(toParent: nil)
self.view.removeFromSuperview()
self.removeFromParent()
}
调用 DataDelegate 到父视图
class ParentView: UIViewController, DataDelegate {
func printTextField(string: String) {
print(string)
}
}
我打算将我的文本字段的数据从子视图传递到父视图,我试试这个代码: https: //jamesrochabrun.medium.com/implementing-delegates-in-swift-step-by-step-d3211cbac3ef https://jamesrochabrun.medium.com/implementing-delegates-in-swift-step-by-step-d3211cbac3ef https:// /www.youtube.com/watch?v=aAmvQU9HccA&t=438s
但它没有用,任何帮助谢谢:)
编辑:添加了我的委托实现代码...
解决方案
因此,根据您已完成声明但未初始化委托的代码。因此,转到您的 ParentView 并在 viewDidLoad 或您准备移动孩子的函数中分配委托,例如:-
toChildView.delegate = self
然后再试一次。:-)
推荐阅读
- javascript - Javascript:如何显示数组中的一定数量的项目并在按钮单击时显示其他项目?
- docker - 无法容器化 NestJS 微服务
- php - 安装 PHP 扩展 xml
- ruby-on-rails - 如何在 Rails 中保存对象之前验证实例化和验证子级
- c# - 如何在 C# WPF 中使用参数绘制圆弧?
- google-sheets - 如何使用 Arrayformula 将百分比报价设置为表中的一列
- c# - ASP.Net 如果数据不存在则添加数据,如果数据存在则更新数据
- java - 詹金斯不支持 Java 16
- c# - 想拿起工具或枪支,但想在统一 c# 中一次只选择一个
- c# - Opentap 无法将“[name].dll”复制到“bin\Debug\Dependencies\[Name].dll”。重试次数超过 10。失败