Swift 中未调用委托方法?

Delegate Method is not called in Swift?

我想在不借助 segue 的情况下将一个 Bool 值从一个视图控制器传递到另一个视图控制器。所以我推荐并获得了代表。

我已经在我的应用程序中申请了代表。但是委托方法没有被调用。我不知道我在哪里犯了错误。

所以请帮助我。

MainViewController

class MainViewController: UIViewController, WriteValueBackDelegate {

    @IBOutlet weak var LoginButton: UIButton!
    var LoggedInL :Bool?

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func writeValueBack(value: Bool) {
        println("Delegate Method")
        if (value == true){
            LoginButton.setTitle("My Profile", forState:UIControlState.Normal)
        }
    }

第二个视图控制器

class LoginController: UIViewController {

    @IBOutlet weak var LoginLabel: UILabel!
    @IBOutlet weak var email: UITextField!

    @IBOutlet weak var pwd: UITextField!
    var LoggedInL :Bool?

    var mydelegate: WriteValueBackDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func onSubmit(sender: AnyObject) {

         Alamofire.request(.GET, "http://www.jive.com/index.php/capp/user_verification/\(email.text)/\(pwd.text)")
            .responseJSON { (_, _, data, _) in

                println(data)
                let json = JSON(data!)
                let name = json["first_name"].stringValue
                let status = json["valid_status"].intValue
                println(status)
                var e = self.email.text
                println(e)
                self.LoginLabel.text = "Hey \(name)!"

                if status == 1{
                    println("Correect")
                     self.LoggedInL = true
                    self.mydelegate?.writeValueBack(true)

                }else {
                     self.LoggedInL = false
                    println("Error")
                }
        }
        navigationController!.popViewControllerAnimated(true)
    }
}

protocol WriteValueBackDelegate {
    func writeValueBack(value: Bool)
}

您没有初始化委托,也不需要,委托通常用于异步回调。改为这样做:

class MainViewController: UIViewController {

    static var sharedInstace : MainViewController?;
    @IBOutlet weak var LoginButton: UIButton!
    var LoggedInL :Bool?

    override func viewDidLoad() {
        super.viewDidLoad()
        MainViewController.sharedInstace = self; //this is better from init function
    }

    func writeValueBack(value: Bool) {
        println("Delegate Method")
        if (value == true){
            LoginButton.setTitle("My Profile", forState:UIControlState.Normal)
        }
    }
}

在登录视图控制器中

MainViewController.sharedInstance?.writeValueBack(true)

MainViewController 中,您需要 LoginController 实例的引用可能带有 IBOutlet,然后在 viewDidLoad

中设置委托
@IBOutlet weak var loginController : LoginController!

override func viewDidLoad() {
    super.viewDidLoad()
    loginController.mydelegate = self
}