无法使用 protocol/delegate 将值从 child VC 传递到 parent VC

Unable to pass a value from the child VC to the parent VC using protocol/delegate

我目前有一个 child VC 添加到 parent VC 的容器视图中,我正在尝试从 child Vc 到 parent VC 使用 protocol/delegate.

我先创建了协议:

protocol ChildToParentProtocol: AnyObject {
    func passValueToParent(value: Bool)
}

然后,为 parent VC 配备协议:

extension ParentVC: ChildToParentProtocol {
    func passValueToParent(value: Bool) {
        print(value)
    }
}

创建了一个从 parent 的容器视图到 IB 中的 child 视图控制器的 segue,名为“childToParentSegue”。然后,将其添加到 parent VC:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? ChildVC, segue.identifier == "childToParentSegue" {
        vc.delegate = self
    }
}

最后,将此添加到 child VC:

weak var delegate: ChildToParentProtocol? = nil
@objc func buttonPressed(sender: UIButton!) {
     delegate?.passValueToParent(value: true)
}

当我按下 child VC 中的按钮时,parent VC 没有接收到值,尽管按钮正在工作。

已更新

我正在使用 addChild(viewController) 和 viewController.didMove(toParent : 自我)

I'm adding the child VC to the parent VC by using addChild(viewController) and viewController.didMove(toParent: self).

这就是问题所在。没有续集。您正在以编程方式呈现 child VC。

您应该在呈现 child VC 的同一位置设置委托。我猜你有这样的代码:

let viewController = ChildVC(...)
addChild(viewController)
viewController.didMove(toParent: self)

在上面几行之后设置委托:

viewController.delegate = self