【发布时间】:2018-06-04 18:09:17
【问题描述】:
当我的数组为空且没有数据可提供给tableView 时,我正在使用tableView.backgroundView 设置一些默认文本。代码有效。
问题是即使有数据,首先它会闪烁“无结果”一秒钟但非常明显,然后tableView 正在重新加载来自阵列的实际数据。我怎样才能解决这个问题?
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
}
更新:
即使我将它添加到它从中获取数据的地方,同样的事情也会再次发生。无数据状态先闪烁,很明显,然后显示实际结果。下面的函数在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
}
}
【问题讨论】:
-
这些代码都不属于
numberOfSections,除了设置计数的几行。numberOfSections在table view的使用过程中可以随时调用很多很多次。 -
好吧,我猜这是个错误。顺便说一句,这是一个最佳答案 - stackoverflow.com/a/28533438/4700495 那我该怎么做?
-
将大部分代码放在它所属的位置 - 您加载数据并填充
comments的位置。 -
尽管获得了所有投票,但该链接中的大多数答案都是错误的。
-
好吧,我已经尝试了你的建议,要么我做的不对,要么没用。因为效果好像是一样的。查看我更新的问题,现在我已经将
numberOfSections方法设置为简单的return numOfSections,因为我已经将 var 设为全局并且loadComments函数可以访问它
标签: arrays swift uitableview uiview