ios - 表视图数据被覆盖
问题描述
我有一个 UITableView。它的单元格包含一个标签,该标签将显示一个问题、一个是按钮和一个否按钮。目标是一一查看问题。首先我调用 API 来获取 viewDidLoad 方法中的问题:
override func viewDidLoad() {
super.viewDidLoad()
tableView.allowsSelection = false
getQuestions(baseComplainID: "1") { (questions, error) in
self.questions = questions
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
在 cellForRowAt 方法中,我将它们一一显示:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? TableViewCell else {
fatalError("Fatal Error")
}
cell.yesButton.isHidden = false
cell.noButton.isHidden = false
if indexPath.row + 1 == displayNumber {
cell.questionLabel.text = questions[indexPath.row].question_name
} else {
cell.yesButton.isHidden = true
cell.noButton.isHidden = true
}
cell.yesButton.addTarget(self, action: #selector(action), for: .touchUpInside)
cell.noButton.addTarget(self, action: #selector(action), for: .touchUpInside)
return cell
}
这是单击是或否时正在执行的操作:
@objc func action(sender: UIButton){
let indexPath = self.tableView.indexPathForRow(at: sender.convert(CGPoint.zero, to: self.tableView))
let cell = tableView.cellForRow(at: indexPath!) as? TableViewCell
cell?.yesButton.isEnabled = false
cell?.noButton.isEnabled = false
if sender == cell?.yesButton {
sender.setTitleColor(.black, for: .normal)
sender.backgroundColor = .green
} else {
sender.setTitleColor(.black, for: .normal)
sender.backgroundColor = .green
}
displayNumber += 1
self.tableView.reloadData()
}
这里我只是更改了按钮的背景颜色并增加了显示编号以显示下一个问题。
所有这一切都很完美,除了当我滚动时,数据被覆盖,有时我发现问题标签为空并且问题相互替换。由于单元可重用性,我知道这是正常的,但我不知道如何解决它。
请问有什么建议吗?
解决方案
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? TableViewCell else {
fatalError("Fatal Error")
}
cell.yesButton.isHidden = false
cell.noButton.isHidden = false
if indexPath.row + 1 == displayNumber {
cell.questionLabel.text = questions[indexPath.row].question_name
} else {
cell.yesButton.isHidden = true
cell.noButton.isHidden = true
}
cell.yesButton.addTarget(self, action: #selector(action), for: .touchUpInside)
cell.noButton.addTarget(self, action: #selector(action), for: .touchUpInside)
return cell
}
我觉得您的问题出在 cellForRowAt 函数中。
你有这个写的
if indexPath.row + 1 == displayNumber { your code here }
但我不确定你为什么需要这个。
你应该在 cellForRowAt 里面做这样的事情
let data = self.questions
data = data[indexPath.row]
cell.questionLabel.text = data.question_name
您不应该将 1 添加到您的 indexPath.row
推荐阅读
- java - java - 如何循环直到前两个元素等于Java中数组的最后两个元素?
- php - Laravel 7 websockets 抛出 404
- ios - 升级到 Xcode 12.5 后的 xcodebuild 问题
- go - 在传递正确的参数时证明模拟的断言失败
- java - 我可以用 sax 库创建 XML 文件吗?
- dictionary - tcl dict:列表值是参数?
- python - 以前的最大值小于 x 有条件
- google-apps-script - 如何将多项选择下拉列表设置为仅在特定范围内工作
- javascript - 如何实现在邮递员中工作文件但不在实际代码中的api
- python - Counter 函数的过滤结果