Search code examples
iosswifttableviewseguenavigationcontroller

Best way to reload vc table view backing from another vc


I'm trying to reload table view in Calculation controller, pressing back navigation button on Setup controller (red arrow on screenshot).

Which is the best way to do it? Thanks !


Solution

  • In a navigation controller its's pretty easy. In Swift the most efficient way is a callback closure, it avoids the overhead of protocol/delegate.

    • In SetupController declare a callback property, a closure with no parameter and no return type

      var callback : (() -> Void)?
      

      and call it in viewWillDisappear. viewWillDisappear is allways called when the back button is pressed.

      override func viewWillDisappear(_ animated: Bool) {
          super.viewWillDisappear(animated)
          callback?()
      }
      
    • In CalculationController assign the callback in prepare(for

      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
          ...
          let setupController = segue.destination as! SetupController
          setupController.callback = { 
              self.tableView.reloadData()
          }