swift - 委托不能使用容器 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 中的按钮时,调用了委托函数但不起作用。我认为问题应该是使用容器视图和委托函数。 在这里下载项目。有什么提示吗?谢谢
解决方案
由于您需要从父母那里调用孩子,因此这里不需要委托,因此将其设为内部实例变量MainViewController
let secondViewController = SecondViewController()
然后用它来调用
secondViewController.sayHi()
推荐阅读
- python - 与二次回归混淆的结果
- arrays - 序列(字符串)由以滑动方式重复另一个序列组成
- javascript - 网页中按键时间的保证范围
- python - 根据 Pandas DataFrame 中的日期时间对象间隔获取值
- javascript - 如何“分类”特定色调的颜色
- reactjs - 在 html id 中使用道具
- spring - WhiteListedAllowFromStrategy 不起作用
- python - 必须告诉用户将 B 更改为 A 需要多少次翻转的代码无法正常工作
- java - 为什么我的应用程序在多次单击 Textview/Views 时会像进入后台模式一样关闭?
- java - reader.nextLine() 出现“找不到符号”错误