简体   繁体   中英

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. I think I also understand how to send data to a parent View Controller through the use of protocols and delegates. But how do I send data to a grandparent 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 . 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.

You can use protocols in this case too. 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)

//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). Let me know if anything is unclear to you.

Hope this will work for you too!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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