iNishinKareem iNishinKareem - 1 month ago 4x
iOS Question

Not able to assign value to text Field during dismissViewController

I have two View Controllers - A & B.
ViewController A has a textfield. on click on textfield of ViewController A, there appears View Controller B which has another Textfield. Clicking done on keyboard of ViewController B, dissmissViewController is called and data of textfield should move from viewController B to A.

I'm not able to pass data from B to A. I'm calling ViewdidLoad() of A right before dissmissviewcontroller. At viewdidLoad() of A, i have this textfieldA.text =textfieldB. it's throwing -

fatal error: unexpectedly found nil while unwrapping an Optional value"


Delegate Pattern:


//Define Protocol
@protocol VC2Delegate {

Class:VC2 {
    //Create Delegate variable
    var delegate:VC2Delegate?

    //method of done clicked
    func btnDoneClicked(sender:UIButton) {

        //call delegate method
        //dismiss view controller



//Conform Protocol
Class:VC1, VC2Delegate {

    //implement delegate method
    func doneClicked(val:String) {
      //assign value to textfield
      vc1TextField.text = val


    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "MySegueFromVC1ToVC2" {
            if let destVC = segue.destinationViewController as? VC2 {
                //assign delegate to VC1
                VC2.delegate = self