Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communication between container view controllers

Tags:

ios

swift

I am new to iOS development and I am stuck with a problem. Here is my application. screenshot What I am trying to achieve is when I click on the switch, it should update the tableview probabilities.

Here is my storyboard : storyboard

I am able to get the changed value of the switch in the DetailViewController (the controller on the left, the ancestor) with a delegate protocol. But now I have no idea on how to broadcast the new value to the DetailChartViewController. The DetailChartViewController is a UIPageViewController containing UITableViewControllers (as seen in the screenshot). So how can I broadcast a new value from child to parent to child ? Do I have to use an observer pattern ? The notification center ?

Any suggestion will be helpful.

like image 665
prbaron Avatar asked Jul 26 '26 21:07

prbaron


1 Answers

Create a var for your detailChartViewController then set it directly. You can assign the var in your prepareForSegue method. When you create a container view you need to set it's identifier for the embedded controller. Then your prepareForSegue method will fire which is where you assign that var to the controller. If you want to access your parent from the children you can either pass a reference to your parent from within the prepareForSegue func or create a protocol/delegate to communicate back(usually preferred).

var detailFormViewController:DetailFormViewController? // Set the identifier for both of these in the identity inspector of these views in the storyboard
var detailViewController:DetailViewController?

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     if segue.identifier == "DetailView" {
         self.detailViewController = segue.destinationViewController as! DetailViewController
         // You can always pass the parent to the child like below although a delegate is a more preferred technique
         self.detailViewController.parentViewController = self
     } else if segue.identifier == "DetailFormViewController" {
         self.detailFormViewController = segue.destinationViewController as! DetailFormViewController
     }
}

func someFunction() {
     // Now that you have a reference to your container view controllers you can access any of their objects directly from your parent view. 
     self.detailViewController.labelSomething.text = "Something"
     self.detailFormViewController.labelSomethingElse.text = "Something else". 
}
like image 88
Mark McCorkle Avatar answered Jul 28 '26 12:07

Mark McCorkle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!