如何在另一个ViewController添加值后刷新TableView?已试StackOverFlow方案无效
Hey there! Let's tackle this table view refresh issue you're facing—it's a super common gotcha, so let's break down the most likely fixes:
1. Trigger reloadData() When Data Updates
The most straightforward issue is that your table view doesn't know the data has changed. You need to explicitly tell it to refresh after updating your data source. The easiest way is to use a callback or delegate to notify your main ViewController when a new person is added.
Example with a Closure Callback
In your "Add Person" view controller:
class AddPersonViewController: UIViewController { // Define a closure to trigger after saving var onPersonSaved: (() -> Void)? @IBAction func saveButtonTapped(_ sender: UIButton) { // 1. Save your new person to data storage (Core Data, UserDefaults, etc.) saveNewPersonToStorage() // 2. Fire the closure to notify the main VC onPersonSaved?() // 3. Navigate back navigationController?.popViewController(animated: true) } }
In your main ViewController (where the table view lives):
class MainViewController: UITableViewController { var persons: [Person] = [] override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let addVC = segue.destination as? AddPersonViewController { // Set up the closure to refresh data and table view addVC.onPersonSaved = { [weak self] in guard let self = self else { return } // Refresh your data source with the latest entries self.loadLatestPersons() // Tell the table view to reload self.tableView.reloadData() } } } func loadLatestPersons() { // Fetch updated data from your storage (replace with your actual logic) persons = YourDataManager.shared.fetchAllPersons() } }
2. Refresh in viewWillAppear
If navigating back via a navigation controller pop, your main VC's viewWillAppear method will be called. You can use this to reload data every time the screen comes into view:
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Reload data and refresh table view loadLatestPersons() tableView.reloadData() }
This is a reliable fallback if callbacks/delegates feel too complex, though it will refresh every time the view appears (not just after adding a person).
3. Verify Your Data Source is Actually Updated
Double-check that your data storage (Core Data, array, etc.) is being properly updated when you add a person. For example:
- If using Core Data, make sure you're saving the managed context after creating the new person object.
- If using a local array, ensure you're appending the new person to the same array that the table view uses as its data source.
4. Avoid Common Pitfalls
- Always use
[weak self]in closures to prevent memory leaks. - Don't forget to call
super.viewWillAppear(animated)if you override that method—skipping it can break UIKit's lifecycle logic. - If you're using
UITableViewController, ensure thetableViewoutlet is properly connected in your Storyboard.
内容的提问来源于stack exchange,提问作者Tonzkie

