iosswiftdelegatesprotocolsuicontainerview

Swift Delegate is never called


I know the question is already here in the forum but I don't know why my delegate doesn't work. I work with them for the first time, by the way.

Here is the code

ViewController:

class ViewController: UIViewController, ContainerViewControllerDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()

        let controller = ContainerViewController()
        controller.containerDelegate = self

    }

    func didScrollChangeAppearanceBarButtonItem(change: Bool) {
        if(change == true){
            print("true")
        }else{
            print("false")
        }
    }

}

ContainerView:

protocol ContainerViewControllerDelegate {
     func didScrollChangeAppearanceBarButtonItem(change: Bool)
}

class ContainerViewController: UIViewController, UIScrollViewDelegate{

    var containerDelegate: ContainerViewControllerDelegate?

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

        if(velocity.y>0) {
            containerDelegate?.didScrollChangeAppearanceBarButtonItem(change: false)
            print("1")

        } else {
            containerDelegate?.didScrollChangeAppearanceBarButtonItem(change: true)
            print("2")
        }
    }
}

What I am trying to do: When I scroll I want to send a bool to my ViewController. When the bool == true I want to something and when the bool == false I want to do something else.

I hope somebody can help me :)


Solution

  • instead of this:

    let controller = ContainerViewController() 
    controller.containerDelegate = self 
    

    create the variable outside viewDidLoad():

    var controller:ContainerViewController! 
    override func viewDidLoad() { 
        super.viewDidLoad() 
        controller = ContainerViewController() 
        controller.containerDelegate = self 
    }
    

    The reason is that the controller being initialized inside the viewDidLoad gets deallocated once the viewDidLoad function reaches its end

    Edit

    I will elaborate, if you are trying to access your other view controller by segue, this is a wrong way. Instead do this:

    self.performSegueWithIdentifier("your identifier", sender: self)
    

    then add a function:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "Your identifier") {
            guard let controller = segue.destination as? ContainerViewController else { return }
            controller.delegate = self
        }
    }