Delegate not called in iOS SWIFT

I created 2 views, one is using a protocol and a delegate. For the first view, the Delegate function is not called.

My FirstView Controller: here I access the delegate function.

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 create a delegate.

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.
    }

}
+4
source share
2 answers

For me, it looks like you are pushing a view controller on which you have not actually set the delegate. If you change the "Next" function, include the line

nextViewController.delegate = self

You should see that the delegation is working. However, you can also remove the creation of "secondController", since it looks like an extra.

+10
source

, , - .

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

, @Eagerod, , ,

durationDel.delegate = self
0

Source: https://habr.com/ru/post/1543446/


All Articles