我有一个tableview,使用带有Firebase的observe侦听器进行更新。
如果我说,更改一些数据,实际的数据结构会更新,我会调用tableView.reloadData(),但是当你将表格中的单元格滚出屏幕时,它只会将数据加载到单元格中,然后重新开启。就像它然后绘制单元格现在它开启和关闭,但使用更新的数据。
如何让这种动态变化?
func getProblems(){
print("getting problems")
let ref = FIRDatabase.database().reference(withPath: "problems")
ref.observe(.value, with: { (snapshot) in
self.problems = []
var newProblems: Array<Problem> = []
let json = JSON(snapshot.value)
//print(json)
for (key, value) in json {
var problemReceived = json[key]
var newProblem = Problem(id: "", user_id: "", title: "", message: "", status: 0, category: 0, image: #imageLiteral(resourceName: "NoImage"), commentCount: 0, distance: 0, date: Date(timeIntervalSinceNow: 5 * 60), user_name: "Derek Sibling", comments: [])
newProblem.id = problemReceived["id"].stringValue
newProblem.user_id = problemReceived["user_id"].stringValue
newProblem.title = problemReceived["title"].stringValue
newProblem.message = problemReceived["message"].stringValue
newProblem.status = problemReceived["status"].intValue
newProblem.category = problemReceived["category"].intValue
newProblem.status = problemReceived["status"].intValue
newProblem.distance = Double(arc4random_uniform(9) + 1)
newProblem.image_url = problemReceived["image_url"].stringValue
newProblem.downloadImage()
newProblem.getComments()
if(newProblem.status != 1){
newProblems.append(newProblem)
}
self.counter = self.counter + 1
if(self.counter == Int(snapshot.childrenCount)){
//self.comments = tempComments
}
}
self.problems = newProblems
self.problems = self.problems.shuffled()
self.tableView.reloadData()
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for : indexPath) as! CustomCell
cell.titleLabel.text = problems[(indexPath as NSIndexPath).row].getTitle()
cell.descriptionLabel.text = problems[(indexPath as NSIndexPath).row].getMessage()
cell.statusLabel.text = problems[(indexPath as NSIndexPath).row].calculateSolved()
cell.messageCountLabel.text = "\(problems[(indexPath as NSIndexPath).row].comments.count)"
cell.distanceLabel.text = "\(problems[(indexPath as NSIndexPath).row].getDistance())km"
cell.problemImage.image = problems[(indexPath as NSIndexPath).row].getImage()
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
var cell:CustomCell = cell as! CustomCell
cell.messageCountLabel.text = "\(problems[(indexPath as NSIndexPath).row].comments.count)"
}