UITableView reloadData()无效求助:点击保存后列表不更新
Hey there! Let's figure out why your UITableView isn't updating when you tap "Save" on the alert. The core issue here is you haven't assigned the table view's dataSource to your view controller. Even though you've implemented the UITableViewDataSource protocol in an extension, the table view has no idea to use your view controller as its data source unless you explicitly tell it to.
Here's how to fix it:
Add this line inside your viewDidLoad() method:
tableView.dataSource = self
Your updated viewDidLoad() will look like this:
override func viewDidLoad() { super.viewDidLoad() self.title="The List" tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") // Connect the table view to its data source tableView.dataSource = self }
Why this works:
A UITableView depends on its dataSource to get critical info: how many rows to display (numberOfRowsInSection) and what content goes into each cell (cellForRowAt). Without setting tableView.dataSource = self, the table view has no clue where to fetch this data—so even when you add items to your names array and call reloadData(), nothing changes because the table view isn't listening to your data source methods.
Quick sanity check for other potential issues:
- You're already calling
reloadData()on the main thread (sinceUIAlertActionclosures run on the main thread by default), so that's not causing the problem here. - Your
UITableViewDataSourcemethods are correctly implemented, so once the data source is connected, they'll start working as expected.
Give that a try, and your table view should start showing new names right after you tap "Save"!
内容的提问来源于stack exchange,提问作者Davoud Nasrabadi

