简体   繁体   English

代表未在SWIFT iOS中调用

[英]Delegate Not Called In SWIFT iOS

I am Created 2 Views, One is and Used Protocol and Delegate. 我创建了2个视图,一个是使用协议和委托。 For first view the Delegate function is not called. 对于第一个视图,不调用Delegate函数。

My FirstView Controller : Here I am Accessing the Delegate Function. 我的FirstView控制器:我在这里访问代理功能。

import UIKit

class NextViewController: UIViewController,DurationSelectDelegate {
    //var secondController: DurationDel?

    var secondController: DurationDel = DurationDel()

    @IBAction func Next(sender : AnyObject)
    {
        let nextViewController = DurationDel(nibName: "DurationDel", bundle: nil)
        self.navigationController.pushViewController(nextViewController, animated: true)
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        secondController.delegate=self
    }

    func DurationSelected() {
        println("SUCCESS")
    }

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

}

My SecondView Controller : Here I Am creating Delegate. 我的SecondView控制器:我在这里创建委托。

import UIKit

protocol DurationSelectDelegate {
    func DurationSelected()
}


class DurationDel: UIViewController {

    var delegate: DurationSelectDelegate?

    @IBAction func Previous(sender : AnyObject) {
        //let game = DurationSelectDelegate()
        delegate?.DurationSelected()
        self.navigationController.popViewControllerAnimated(true)
    }


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

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

}

To me, it looks like you're pushing a view controller that you haven't actually set the delegate for. 对我来说,看起来你正在推动一个你没有实际设置委托的视图控制器。 If you change your "Next" function, to include the line 如果更改“下一步”功能,则包括该行

nextViewController.delegate = self

You should see that the delegation works. 你应该看到代表团的工作。 In doing this, you can also probably remove the creation of "secondController", as it looks like that's redundant. 在执行此操作时,您还可以删除“secondController”的创建,因为它看起来是多余的。

The naming convention you have followed would confuse fellow developers in your team. 您遵循的命名约定会让您的团队中的开发人员感到困惑。 The instance should have been 实例应该是

let durationDel = DurationDel(nibName: "DurationDel", bundle: nil)

And then as @Eagerod mentioned, the delegate you would set is 然后就像@Eagerod提到的那样,你要设置的代表是

durationDel.delegate = self

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM