无法在委托回调方法中更新文本字段

时间:2017-02-07 05:53:01

标签: ios iphone swift

我已在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)
    }

2 个答案:

答案 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)

你的结果将是:

enter image description here

查看THIS示例以获取更多信息。

并且不要忘记从故事板中嵌入LoginViewControllernavigationController。如演示项目所示。