我已在LoginViewController
中定义的RegistrationViewController
中实施了委托。回调函数正在调用,但问题是我无法在委托方法中更新textfield
LoginViewController
。
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)
}
答案 0 :(得分:1)
这意味着您在寄存器VC的self.storyboard?.instantiateViewController(withIdentifier: "login")
上再次分配内存,默认情况下您的委托的原因是nil。
@IBAction func register(_ sender: Any) {
self.delegate?.onUserRegistrationCompletion(number: "05010101010")
self.dismiss(animated: true, completion:nil)
}
答案 1 :(得分:1)
我建议您使用navigationController
。
您可以通过这种方式推送到下一个视图:
let controller = storyboard?.instantiateViewController(withIdentifier: "registration") as! RegistrationViewController
controller.delegate = self
self.navigationController?.pushViewController(controller, animated: true)
当您想要返回上一个视图时,请使用以下代码:
self.delegate?.onUserRegistrationCompletion(number: "05010101010")
self.navigationController?.popViewController(animated: true)
你的结果将是:
查看THIS示例以获取更多信息。
并且不要忘记从故事板中嵌入LoginViewController
到navigationController
。如演示项目所示。