Reputation: 154
I have a number of entries (cells) in a UITableView in Swift which each represent a "song" that each user can select. The titles of the songs that have not yet been completed are represented by question marks and the others are displayed normally. The songs completed by the user are stored in a firebase database which is immediately read at the beginning of the UITableViewController lifecycle and stored in a global dictionary I called temp_dict.
The dictionary temp_dict is of the form
Key = "02": Value = "Complete", Key = "03": Value = "Complete", etc.
The problem is that the loading of the data into this Dictionary does not happen immediately and the initial call of the following "loading the cells" function:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {}
occurs before I have the information from the firebase to decide which ones have been completed or not.
I am now in a strange situation where the question marks will only appear after I have scrolled down to the bottom (there are around 30 cells) then scroll back up again. I believe this occurs because each cell is removed and added again when it is removed and reappears on the screen
What I've tried: I've tried using self.tableView.reloadData() at various stages but it does nothing for some reason.
class MainTableViewController: UITableViewController {
...
override func tableView(_ tableView: UITableView, cellForRowAt
indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "cell",
for: indexPath)
myCell.textLabel?.text = songs[indexPath.row].title
myCell.detailTextLabel?.text = songs[indexPath.row].artist
if (self.temp_dict[String(indexPath.row+1)] != "Complete") {
myCell.textLabel?.text = question_marks(s :
songs[indexPath.row].title)
myCell.detailTextLabel?.text = question_marks(s :
songs[indexPath.row].artist)
}
num_times_called = num_times_called + 1
return myCell
}
...
}
** songs is an array of song objects which have attributes of title, artist, song number etc.
Results:
Right now, I am greeted with all cells being entirely question marks when I start up this viewcontroller. When I scroll to the bottom and scroll back up, the songs that have been completed are now suddenly displayed as no longer question marks (which is what I want but I want this to happen immediately).
Summary:
I need a way to automatically reload all the cells on a uitableview immediately following the occurence of a particular event.
Thanks for any help.
Upvotes: 0
Views: 438
Reputation: 490
Mr.P's answer is almost correct. I suggest to reload tableview on main thread:
var temp_dict: [String: String] {
didSet {
DispatchQueue.main.async {
tableView.reloadData()
}
}
}
Upvotes: 1
Reputation: 1430
Add a property observer to your temp_dict
object so that it will reload the table view automatically when it is updated
var temp_dict: [String: String] {
didSet {
tableView.reloadData()
}
}
Upvotes: 0