I'm using the tableView.backgroundView
to set some default text when my array is empty and there's no data to feed to the tableView
. The code works.
The problem is that EVEN If there's data, first it sort of flashes the "No results" for a split of a second but quite obvious and then the tableView
is being reloaded with actual data from the array. How can I fix this?
func numberOfSections(in tableView: UITableView) -> Int {
var numOfSections: Int = 1
if comments.count > 0 {
numOfSections = 1
tableView.backgroundView = nil
}
else {
numOfSections = 0
activityIndicator.stopAnimating()
let noDataLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
noDataLabel.text = "Silence in the comments! \r\nSay something..."
noDataLabel.textColor = UIColor.black
noDataLabel.textAlignment = .center
tableView.backgroundView = noDataLabel
tableView.backgroundView?.backgroundColor = UIColor.hex("D8D8D8")
tableView.separatorStyle = .none
}
return numOfSections
}
UPDATE:
Even when I add it in the place where it gets the data from, the same thing happens again. The no data state flashes first and its obvious and then it shows the actual results. The function below is called in the viewWillAppear
func loadComments() {
activityIndicator.startAnimating()
if let id = postId {
Api.Post_Comment.REF_POST_COMMENTS.child(id).observe(.childAdded, with: {
snapshot in
Api.Comment.observeComments(withPostId: snapshot.key) {
comment in
self.fetchUser(uid: comment.uid!, completed: {
self.comments.append(comment)
self.activityIndicator.stopAnimating()
self.tableView.reloadData()
if self.comments.count > 0 {
self.numOfSections = 1
self.tableView.backgroundView = nil
}
else {
print("ELSE")
}
})
}
})
print("No data")
self.numOfSections = 0
self.activityIndicator.stopAnimating()
let noDataLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: self.tableView.bounds.size.height))
noDataLabel.numberOfLines = 0
noDataLabel.text = "Silence in the comments! \r\nSay something..."
noDataLabel.textColor = UIColor.darkGray
noDataLabel.textAlignment = .center
self.tableView.backgroundView = noDataLabel
self.tableView.backgroundView?.backgroundColor = UIColor.hex("D8D8D8")
self.tableView.separatorStyle = .none
}
}