简体   繁体   English

如何在Swift中将消息发送到祖父母View Controller

[英]How to send message to grandparent View Controller in Swift

I understand how to send data to a child View Controller when calling it with a segue. 我了解在使用segue调用数据时如何将数据发送到子级 View Controller I think I also understand how to send data to a parent View Controller through the use of protocols and delegates. 我想我也了解如何通过使用协议和委托将数据发送到父级 View Controller But how do I send data to a grandparent View Controller? 但是,如何将数据发送到祖父母 View Controller?

Options that I've considered: 我考虑过的选项:

  • Send the data to the parent and have the parent send it to the grandparent. 将数据发送给父母,并让父母将其发送给祖父母。 But this seems like a lot of extra work when then parent doesn't need to know. 但是,当父母不需要知道时,这似乎是很多额外的工作。
  • Use NSNotificationCenter . 使用NSNotificationCenter But (1) it is only the grandparent that needs to know, not the whole world, and (2) from the scant Swift documentation that I've found, NSNotificationCenter seems very unSwiftlike. 但是(1)只需要了解祖父母,而不是整个世界,以及(2)从我发现的Swift文档很少, NSNotificationCenter看起来很不像Swift。

You can use protocols in this case too. 在这种情况下,您也可以使用protocols I have done this way : 我这样做:

In the current controller(lets say grandchild controller), just intialize your grandparent controller and set delegate (same as you do in prepareForSegues in case of parent controller) current控制器中(让我们说grandchild控制器),只需初始化您的grandparent控制器并设置delegate (与在parent控制器的prepareForSegues中所做的相同)

//use this lines when you want call the grandparent controller
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let grandParentVC= storyboard.instantiateViewControllerWithIdentifier("grandPVC") as! UIViewController
grandParentVC.delegate = self
//now call your delegate method here

As you specified, you know protocols (the links you included). 如您所指定的,您知道protocols (包括的链接)。 Let me know if anything is unclear to you. 让我知道您是否不清楚。

Hope this will work for you too! 希望这也对您有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM