[英]Delegate multiple view controllers
我有连接到2个视图控制器的主视图控制器。 我做了didRecive(data:Data)委托函数的协议。
protocol MainViewControllerDelegate: class {
func didReciveDepartment(response:DepartmentResponse)
}
在主视图控制器中,我声明委托var。
weak var delegate: DepartmentMainViewControllerDelegate?
在准备segue时,我将此代表设置为viewCotnroller。 像这样-
if segue.identifier == "productsEmbedded" {
let vc = segue.destination as! DepartmentProductsViewController
delegate = vc
}
if segue.identifier == "shopsEmbedded" {
let vc = segue.destination as! DepartmentShopsViewController
vc.delegate = self
delegate = vc
}
我在DepartmentShopsViewController中仅连接了行为委托触发器,而DepartmentProductsViewController无法获取此委托,我评论说商店和产品都具有此委托,因此这意味着我不能对2个控制器使用相同的委托?
这些是在对象之间传递消息的许多方法。 您可以使用Delegate和NSNotificationCentre传递数据。 主要区别在于代表,一个指定的对象接收消息,而任何数量的对象在发布时都可以接收通知。 您可以检查此先前的SO查询以获取详细信息。
来吧,你忘了一条线
vc.delegate = self
该代码应如下所示
if segue.identifier == "productsEmbedded" {
let vc = segue.destination as! DepartmentProductsViewController
vc.delegate = self //Add this Line
delegate = vc
}
if segue.identifier == "shopsEmbedded" {
let vc = segue.destination as! DepartmentShopsViewController
vc.delegate = self
delegate = vc
}
对于委托,您必须像这样实现
//Declare protocol
protocol MainViewControllerDelegate {
func didReciveDepartment(response:DepartmentResponse)
}
class DepartmentProductsViewController: UIViewController {
// MARK: - Variable Declaration.
var delegate: MainViewControllerDelegate?
}
class DepartmentShopsViewController: UIViewController {
// MARK: - Variable Declaration.
var delegate: MainViewControllerDelegate?
}
class MainViewController: UIViewController, MainViewControllerDelegate {
//Push ViewController with segue and use delegate property
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "productsEmbedded"{
let vc = segue.destination as! DepartmentProductsViewController
vc.delegate = self
} else if segue.identifier == "shopsEmbedded" {
let vc = segue.destination as! DepartmentShopsViewController
vc.delegate = self
}
}
//MARK: Implement MainViewControllerDelegate Methods.
func didReciveDepartment(response: DepartmentResponse) {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.