Rob B
Rob B

Reputation: 1309

How to read value of parent ViewController in swift

I have a ViewController that has an embed in PageViewController. The page ViewController of course instantiate two more viewControllers that displays content. My problem is that the two instantiated viewControllers need to read a value that is created in the ParentViewController and I don't know how can I access this value.

Any Idea?? Thanks

Upvotes: 0

Views: 346

Answers (2)

Amr
Amr

Reputation: 290

To access the root controller you can try:

  guard let rootController = self.navigationController?.viewControllers.first as? YourRootController else {return}     

Then you can access the needed value like:

 guard let value = rootController.YourValue else {return}

Upvotes: 1

Raja Vijaya kumar
Raja Vijaya kumar

Reputation: 51

If the values are static that you will be passing to the page view controllers just create a variable inside view controller and assign the value to it before presenting the view controller.

class ParentViewController: UIViewController {
      var yourValue: String = "Something you want to pass"
      .....

      func setupPageViewController() {
           let vc1 = ChildViewController()
           let vc2 = ChildViewController()
           vc1.value = yourValue
           vc2.value = yourValue
           .....
           .....
           pageViewController.setViewControllers([vc1, vc2], direction: .forward, animated: true)
      }
}

Or if you want to get notified whenever there is a value change in the parent view controller I would suggest you to use NSNotificationCenter. Refer this link for NSNotificationCenter tutorial.

https://medium.com/@JoyceMatos/using-nsnotificationcenter-in-swift-eb70cf0b60fc

Upvotes: 0

Related Questions