iosuicontainerviewswift3.2

Pass values from container view to parent view controller


Im new to swift and i would like pass an array from my container view to parent view.I have created the container view using story board, but the container view appears and disappears programatically as shown below:

//in parent view controller, inside viewDidLoad()
CameraView.isHidden  = true

//in child view controller, on click of button,
let parent = self.parent as! DiaryEntryViewController
parent.CameraView.isHidden  = true

I want the data selected to be shown whenever i click the button to display container view. I don't know how to pass values from child view controller to parent view controller and where can I should be able to access the values.These values need to accessed inside a function which is called on click of another button inside parent view controller.


Solution

  • Steps to do that.

    1. Your container view must contain a embed segue to the child view controller, name that segue something like this.... "homeToContainer" (See the attached Image) Add Embed segue name

    2. Add this method to your parent View controller (DiaryEntryViewController )

      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
              if let vc = segue.destination as? ChildViewController,
                  segue.identifier == "homeToContainer" {
                  vc.delegate = self
              }
      }
      
    3. Add Protocol and its variable in ChildViewController:

          protocol ChildToParentProtocol:class {
      
      
              func buttonClickedByUser()
              func needToPassInfoToParent(with value:Int)
      
          }
      
      
          class ChildViewController: UIViewController {
      
              weak var delegate:ChildToParentProtocol? = nil
      
              @IBAction func createTourPressed(_ sender: UIButton) {
                  // Call here delegate methods to tell parent about the action
                  delegate?.buttonClickedByUser()
      
              }
      
          }
      
    4. In the last in your parent ViewController, add this Extension:

              extension DiaryEntryViewController:ChildToParentProtocol {
      
                  func buttonClickedByUser() {
      
                  }
                  func needToPassInfoToParent(with value:Int) {
      
      
                  }
              }