gpt4 book ai didi

ios - TableView 数据被覆盖

转载 作者:行者123 更新时间:2023-12-01 21:58:09 26 4
gpt4 key购买 nike

我有一个 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

关于ios - TableView 数据被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60995585/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com