Omar Dadabhoy
Omar Dadabhoy

Reputation: 59

How to reload data in UITableView when popping view controller

If I have two ViewControllers one which contains a UITableView and another which updates data in the tableView. How would I reload the table data once I pop of the viewController and go back to the view with the tableView?

I already tried using viewDidAppear

Upvotes: 1

Views: 3890

Answers (3)

app4g
app4g

Reputation: 840

I was having similar issue and using viewWillAppear or viewDidAppear did not help me to reload the tableview.

I solved my situation by putting the reloadData() call within the unwindSegue

  @IBAction func unwindToVCSetupDataScreen(_ unwindSegue: UIStoryboardSegue) {
    /// Nothing is actually needed here
    /// https://www.youtube.com/watch?v=WaSlHXNah7E @6:25
    /// CTRL-Drag from Back button to the "exit" square at the very top of VC
    tableView.reloadData()
  }

Upvotes: 0

vdmzz
vdmzz

Reputation: 261

You may try doing something like this:

class TableViewController: UITableViewController {

    func showUpdatingViewController() {
        let vc = UpdatingViewController()

        vc.onUpdate = { [weak self] in
            self?.tableView.reloadData()
        }

        navigationController?.pushViewController(vc, animated: true)
    }

}

class UpdatingViewController: UIViewController {

    var onUpdate: (() -> Void)?

    func updatesFinished() {
        onUpdate?()
        dismiss(animated: true, completion: nil)
    }

}

Upvotes: 0

rs7
rs7

Reputation: 1630

You could use viewWillAppear just like Rajesh suggested:

override func viewWillAppear(_ animated: Bool) {
    tableView.reloadData()
}

Or you could use a callback function to pass data and reload view controller 1's tableview.

In ViewController 2, define your callback function:

// Callback function
var callbackResult: ((data) -> ())?

And call it before going back to ViewController 1:

    callbackResult?(data)
    self.navigationController?.popViewController(animated: true)

In ViewController 1, use the callback function's closure to collect the result and reload your tableView. This can happen inside prepareForSegue, for example:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToViewController2" {
        let destinationVC = segue.destination as! ViewController2
        // Set any variable in ViewController2
        destinationVC.callbackResult = { result in
        // assign passing data etc..
        self.tableView.reloadData()
        }
    }
 }

Upvotes: 2

Related Questions