iNishinKareem iNishinKareem - 2 months ago 5
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"

Answer

Delegate Pattern:

ViewController2:

//Define Protocol
@protocol VC2Delegate {
    doneClicked(val:String)
}

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

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

        //call delegate method
        delegate.doneClicked(vc2TextField.text)
        //dismiss view controller
        self.dismissViewController......
    }

}

ViewController1:

//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
            }
        }
    }
}