skip to Main Content

I want to pass my data from child view controller to parent view controller.

I’m just moving the child view to the top of the parent view, here is my code:

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let toChildView = storyBoard.instantiateViewController(identifier: "toChildView")
                        
// show child view
self.addChild(toChildView)
toChildView.willMove(toParent: self)
toChildView.view.frame = self.view.bounds
self.view.addSubview(toChildView.view)
toChildView.didMove(toParent: self)

Here is the delegate:

protocol DataDelegate {
    func printTextField(string: String)
}

I added variable delegate to my Child View

var delegate: DataDelegate?

And send the data to Parent View

@IBAction func btnSend(_ sender: Any) {
    delegate?.printTextField(string: textField.text)
}

And close the Child View, like:

@IBAction func btnClose(_ sender: Any) {
    // back to parent view
    self.willMove(toParent: nil)
    self.view.removeFromSuperview()
    self.removeFromParent()
}

Calling the DataDelegate to Parent View

class ParentView: UIViewController, DataDelegate {
    func printTextField(string: String) {
        print(string)
    }
}

Im planning to pass the data of my text field from child view to parent view, I try this codes:
https://jamesrochabrun.medium.com/implementing-delegates-in-swift-step-by-step-d3211cbac3ef
https://www.youtube.com/watch?v=aAmvQU9HccA&t=438s

but it didn’t work, any help thanks 🙂

EDITED: Added my delegate implementation code…

2

Answers


  1. So as per the code you have done with declaration but not initialized the delegate. So go to you ParentView and assign the delegate in viewDidLoad or in the function where you prepare to move on child like:-

    toChildView.delegate = self
     
    

    And try again. 🙂

    Login or Signup to reply.
  2. you will not get delegate property in parent view as it is member of childView. You can do following

    self.addChild(toChildView)
    toChildView.delegate = self
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search