【问题标题】:Swift - Pass data from Child View to Parent ViewSwift - 将数据从子视图传递到父视图
【发布时间】:2020-12-04 06:43:46
【问题描述】:

我想将我的数据从子视图控制器传递到父视图控制器。

我只是将子视图移动到父视图的顶部,这是我的代码:

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://www.youtube.com/watch?v=aAmvQU9HccA&t=438s

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

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

【问题讨论】:

  • Delegate 是满足您要求的好方法。因此,在您提供的教程链接中实施时,您可能会错过一些东西。如果您在这里向我们展示您的委托实现代码会更好。
  • 我编辑我的代码。

标签: ios swift xcode


【解决方案1】:

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

toChildView.delegate = self
 

然后再试一次。 :-)

【讨论】:

  • 当我尝试代码时出现错误,它说“'UIViewController' 类型的值没有成员'delegate'”
  • 您必须先进行类型转换,例如:- 在问题中-> 用下面的行替换第二行。 let storyboard = UIStoryboard(name: "Main", bundle: nil) if let toChildView= storyboard.instantiateViewController(withIdentifier: "toChildView") as? toChildView { toChildView.delegate = self }
  • 总是养成给 ViewControllers 命名的习惯,就像在你的情况下它必须是 - ToChildViewController 和 ParentViewController。因为在 swift View 和 ViewController 中都是不同的。
【解决方案2】:

您不会在父视图中获得委托属性,因为它是 childView 的成员。您可以执行以下操作

self.addChild(toChildView)
toChildView.delegate = self

【讨论】:

    猜你喜欢
    • 2013-11-08
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多