Faisal Khalid Faisal Khalid - 4 years ago 102
Swift Question

Cannot update textfield in delegate callback method

I have implemented delegate in

LoginViewController
defined in
RegistrationViewController
. Callback function is calling but the problem is that I am not able to update the
textfield
of
LoginViewController
in delegate method.

LoginViewController.swift

import UIKit

class LoginViewController :UIViewController,RegisterViewDelegate {

@IBOutlet weak var mobileNumber: UITextField!

@IBAction func showRegistrationView(_ sender: Any) {

let controller = storyboard?.instantiateViewController(withIdentifier: "registration") as! RegistrationViewController
controller.delegate = self
present(controller, animated: false, completion: nil)
}

func onUserRegistrationCompletion(number: String) {
print(number) // output is 05010101010
DispatchQueue.main.async {
self.mobileNumber.text! = number
print(self.mobileNumber.text!) . // output is empty
}

}



}


RegistrationViewController.swift

import UIKit

class RegistrationViewController: UIViewController {

weak var delegate:RegisterViewDelegate?

@IBAction func register(_ sender: Any) {
self.delegate?.onUserRegistrationCompletion(number: "05010101010")
let controller = self.storyboard?.instantiateViewController(withIdentifier: "login")
present(controller!, animated: false, completion: nil)
}

}


protocol RegisterViewDelegate:class {
func onUserRegistrationCompletion(number:String)
}

Answer Source

it means you allocating the memory again on self.storyboard?.instantiateViewController(withIdentifier: "login") in Register VC, that the reason your delegate is by default goes to nil.

@IBAction func register(_ sender: Any) {
        self.delegate?.onUserRegistrationCompletion(number: "05010101010")
         self.dismiss(animated: true, completion:nil) 
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download