首页 > 解决方案 > 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

但它没有用,任何帮助谢谢:)

编辑:添加了我的委托实现代码...

标签: iosswiftxcode

解决方案


因此,根据您已完成声明但未初始化委托的代码。因此,转到您的 ParentView 并在 viewDidLoad 或您准备移动孩子的函数中分配委托,例如:-

toChildView.delegate = self
 

然后再试一次。:-)


推荐阅读