委托无法使用容器 ViewController

Delegate doesn't work using a container ViewController

在我的 MainViewController 中,我设置了一个按钮和一个容器视图,其中包含一个 SecondViewController:

let secondViewController = SecondViewController()
secondViewController.willMove(toParent: self)
containerView.addSubview(secondViewController.view)
secondViewController.view.frame = containerView.bounds
secondViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.addChild(secondViewController)
secondViewController.didMove(toParent: self)

我设置了我的委托协议:

protocol SayHiDelegate {
    func sayHi()
}

在 MainViewController 内部:

var delegate: SayHiDelegate?

@objc func buttonTapped() {
    delegate?.sayHi()
}

我在我的 SecondViewController 中设置了委托函数

func sayHi() {
    label.text = "HI"
}

在 SecondViewcontroller viewDidLoad:

let vc = MainViewController()
vc.delegate = self

在这个项目中我没有使用故事板。 问题是,当我点击 MainViewController 中的按钮时,委托函数被调用但不起作用。 我认为问题应该出在使用容器视图和委托函数上。 Here 下载项目。 有什么提示吗?谢谢

因为您需要从 parent 调用 child 那么这里不需要委托,将其设为 MainViewController

中的实例变量
let secondViewController = SecondViewController()

然后用它来调用

secondViewController.sayHi()

在您的代码中添加这一行

self.delegate = secondViewController

检查你的委托是否为 nil 因为你没有分配 secondViewController

的引用