Search code examples
iosswift3collectionviewuicontainerview

Accessing parent view buttons in container view controller


I have a collection view controller inside of a container view and buttons on the parent view - I need my container view to be able to access the button outlets from my parent view so that I can detect when buttons are clicked in order modify my collection view (in container view) accordingly.

I tried to use preparesegue function but I couldn't get the code I had found to work.


Solution

  • One option is to use NotificationCenter, have your buttons post the notification, and have your child view controller listen for them.

    For example, in the parent VC, post the notification in the function called when a button is tapped, like so:

    @IBAction func buttonTapped(_ sender: UIButton) {
         NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ButtonTapped"), object: nil, userInfo: nil)
    }
    

    In the child VC that needs to respond to the button tap, place the following code in viewWillAppear: to set the VC as a listener for that specific notification:

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(handleButtonTap(_:)), name: NSNotification.Name(rawValue: "ButtonTapped"), object: nil)
    }
    

    In the same view controller, add the handleButtonTap: method mentioned above. When the "ButtonTapped" notification comes in, it will execute this method.

    @objc func handleButtonTap(_ notification: NSNotification) {
        //do something when the notification comes in
    }
    

    Don't forget to remove the view controller as an observer when it is no longer needed, like this:

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }