Search code examples
swiftparent-childios-charts

how do I refresh a childViewControler object when an action occurs on the parent viewControler


I have embedded a child ViewControler into my mainViewControler and it displays a graph. the main view controller includes an input field and a save button. I wish to have the graph in the childViewControler reload its data when the save button is taped. the childViewControler includes a function

func refresh() {
        fetchTransactionsAndCalculateTotals()
        generateChartData()
        setChart()}

that I would like to call. I have setup a segue from the main controller to the child controller,

enum Segues {
        static let toInOutBar = "toInOutBars"
    }

override func prepare(for segue: UIStoryboardSegue, sender: UIButton?) {
           if segue.identifier == Segues.toInOutBar {
               let destVC = segue.destination as! InOutBarViewController
            destVC.refresh()
           }
       }

I am struggling to get further than this, I have tried to call this function from myUIButton action without success.

Thanks for any support


Solution

  • You should link an IBAction on the touchUpInside action of the button and get your child VC using the children property.

    @IBAction func refreshClicked(_ sender: UIButton) 
    {
        guard let vcChild = self.children.first as? InOutBarViewController else { return; }
        vcChild.refresh()
    }