【发布时间】:2020-04-02 15:46:30
【问题描述】:
我有一个 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()
}
这里我只是改变按钮的背景颜色并增加显示编号以显示下一个问题。
除了滚动时,所有这些都完美无缺,数据被覆盖,有时我发现问题标签为空并且问题相互替换。由于单元格可重复使用,我知道这是正常的,但我不知道如何解决。
有什么建议吗?
【问题讨论】:
-
细胞被重复使用。将所有信息保留在数据模型中,然后修改模型并重新加载行。
标签: ios swift uitableview tableview