首页 > 解决方案 > UITableView reloadData() 不能快速工作?

问题描述

我有一个试图从 Firebase 填充的 tableView,但我遇到了 reloadData() 的问题,它不会刷新表格。

这是我的代码:

 func showAnswers(pos: Int, name: String){
    let n = name
                
    answersReference.observe(DataEventType.value, with: {(snapshot) in
        if(!snapshot.exists()){
            
        }else{
            let answers = snapshot.children
            
            for answer in answers{
                let answersFromDB = AnswerFromDBObject()
                answersFromDB.setQuestion(question: (answer as! DataSnapshot).key)
                
                let ansData = (answer as! DataSnapshot).children
                
                for a in ansData{
                    answersFromDB.setAnswer(answer: (a as! DataSnapshot).key)
                }

                print("firebase answer: \(answersFromDB.getAnswer())")

                self.answerFromDBObject += [answersFromDB]
            }

            print("array count: \(self.answerFromDBObject.count)")

            self.userInfoAnwers.text = NSLocalizedString("users_questions", comment: "").replacingOccurrences(of: "(usernamehere)", with: n)
            self.answersTable.reloadData()

        }
    })
}

还有我的 tableView 委托方法:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return answerFromDBObject.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "answersCell") as! SeeAnswersCell
    
    let answer = answerFromDBObject[indexPath.row]
    
    cell.question.text = answer.getQuestion()
    cell.answer.text = answer.getAnswer()
    
    return cell
}

这些是控制台上的打印方法:

firebase 答案:红色
firebase 答案:精细
firebase 答案:伦敦
阵列数:3

标签: iosswiftuitableviewreloaddata

解决方案


  1. 在最后 } 之后试试这个

    DispatchQueue.main.async { self.answersTable.reloadData() }

您这样做是为了能够在主线程中重新加载它

  1. 检查 tableView 委托和数据源已连接

  2. 如果您使用的是 Xib 单元,请检查它是否已注册


推荐阅读