How to update data in tableview using swift?

I currently have 3 quick files: ManualViewController, AutoViewController, Main

ManualViewController is a UIViewController with a table view. AutoViewController is a UIViewController with several buttons. The main one is just a quick file with all the data for a table view.

ManualViewController and AutoViewController are controlled using the TabBarController.

When the application starts, the original content found in Main.swift is loaded into the table view. When I go to the next view, that is, AutoViewController and click on the button to change the data in Main.swift, the data changes. The problem is that when I return to ManualViewController, the table still contains old data, not the updated one.

I also tried this:

override func viewWillAppear(animated: Bool) { super.viewWillAppear(false) self.tableView.reloadData() } 

It still does not work.

+6
source share
2 answers

You can use NSNotificationCenter to update your tableView from another view.

Your declaration -addObserver: should be this way in your tableView Controller in viewDidLoad :

 override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshTable:", name: "refresh", object: nil) } 

And your function for this addObserver will like it:

  func refreshTable(notification: NSNotification) { println("Received Notification") self.tableView.reloadData() } 

Now you can send notifications like this when you go to your tableView controller:

 NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: nil, userInfo: nil) 

Check out the IT sample project for more information.

Hope this helps you.

+3
source

For other users who just want to learn how to reload data in a UITableView , just follow these steps:

 self.tableView.reloadData() 

(Details of the accepted answer make it difficult to find.)

+1
source

Source: https://habr.com/ru/post/989715/


All Articles