如何在 Swift 中向祖父视图控制器发送消息
How to send message to grandparent View Controller in Swift
我通过使用协议和委托了解 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。但是如何将数据发送到 grandparent View Controller?
我考虑过的选项:
- 将数据发送到 parent 并让 parent 将其发送到 grandparent。但是当 parent 不需要知道时,这似乎需要做很多额外的工作。
- 使用
NSNotificationCenter
。但是 (1) 只有盛大 parent 需要知道,而不是整个世界,并且 (2) 从我发现的稀缺 Swift 文档中,NSNotificationCenter
似乎非常不Swift喜欢。
您也可以在这种情况下使用 protocols
。我这样做了:
在 current
控制器中(比如说 grandchild
控制器),只需初始化您的 grandparent
控制器并设置 delegate
(与您在 [=16= 中所做的相同) ] 在 parent
控制器的情况下)
//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
正如您指定的那样,您知道 protocols
(您包含的链接)。如果您有任何不清楚的地方,请告诉我。
希望这对你也有用!
我通过使用协议和委托了解 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。但是如何将数据发送到 grandparent View Controller?
我考虑过的选项:
- 将数据发送到 parent 并让 parent 将其发送到 grandparent。但是当 parent 不需要知道时,这似乎需要做很多额外的工作。
- 使用
NSNotificationCenter
。但是 (1) 只有盛大 parent 需要知道,而不是整个世界,并且 (2) 从我发现的稀缺 Swift 文档中,NSNotificationCenter
似乎非常不Swift喜欢。
您也可以在这种情况下使用 protocols
。我这样做了:
在 current
控制器中(比如说 grandchild
控制器),只需初始化您的 grandparent
控制器并设置 delegate
(与您在 [=16= 中所做的相同) ] 在 parent
控制器的情况下)
//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
正如您指定的那样,您知道 protocols
(您包含的链接)。如果您有任何不清楚的地方,请告诉我。
希望这对你也有用!