首页 > 解决方案 > 委托不能使用容器 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 中的按钮时,调用了委托函数但不起作用。我认为问题应该是使用容器视图和委托函数。 在这里下载项目。有什么提示吗?谢谢

标签: swiftxcodecontainersappdelegateswift-protocols

解决方案


由于您需要从父母那里调用孩子,因此这里不需要委托,因此将其设为内部实例变量MainViewController

let secondViewController = SecondViewController()

然后用它来调用

secondViewController.sayHi()

推荐阅读