Reputation: 650
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)
}
Upvotes: 0
Views: 75
Reputation: 71854
I suggest you to use navigationController
.
and you can push to next view this way:
let controller = storyboard?.instantiateViewController(withIdentifier: "registration") as! RegistrationViewController
controller.delegate = self
self.navigationController?.pushViewController(controller, animated: true)
and when you want to go back to previous view use this code:
self.delegate?.onUserRegistrationCompletion(number: "05010101010")
self.navigationController?.popViewController(animated: true)
And your result will be:
Check THIS sample for more info.
And don't forget to Embed In your LoginViewController
into navigationController
from storyboard. as shown in demo project.
Upvotes: 1
Reputation: 82759
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)
}
Upvotes: 1