Pass data from Parent UIviewController to a Container (ChildViewController) every time the value is changed

112 Views Asked by At

I have a UIViewController that has two containers and each Container is related to a UIViewController for some specific functionalities.

For people who are devaluating my question, it will be more helpful and appreciated if you put me on the right path instead.

what I am trying to do is pass data from the parent ViewController to the childViewControllers

  • I tried it using the protocol/delegate: But the problem is, I couldn't assign the delegate to the childViewContainer since it doesn't have an instance from the parent.

  • My second try was using the prepare function, but it doesn't work as well since the two containers load once the parent loads at first. so if the value is changed in the parentViewController I can't pass it again to the child.

enter image description here

Any Idea, please?

1

There are 1 best solutions below

0
Elin On BEST ANSWER

After a deeper digging I was able to find a solution for my own question. here I am going to post if anyone else needs it in the future

so, first of all, I need it to lunch the ChildContoller from the parent controller and not from the storyboard ( so I deleted the segue between the parent and the child. create a variable for childController like that:

 lazy  var firstChildViewController: FirstChildViewController =  {
        let storynoard = UIStoryboard(name: "Main", bundle: nil)
        let viewController = storynoard.instantiateViewController(identifier: "firstChild") as! FirstChildViewController
    self.addChild(viewController)
    self.view.addSubview(viewController.view)
        return viewController
        
    }()

same thing for the other one if you have two children

and then in the viewDidLoad:

   override func viewDidLoad() {
        
        super.viewDidLoad()
        firstChildViewController.view.isHidden  = false
        secondChildViewController.view.isHidden = true
    }

and then in the FirstChildViewController:

    override func viewDidLoad() {
    
    super.viewDidLoad()
    if let parent = self.parent as? ParentViewController {
     parent.delegate = self
 }

}

And the problem is solved Hope it helps someone