我有一个tableview,并在每个单元格中有一个复选框。我也有一个“全选”按钮。迭代通过TableViewCells跳过一些
我的问题是,当我点击选择所有我想更新所有复选框到选中状态。所以从100个单元的列表中,全部被检查,但每13个单元都没有。为了使它更清晰,在我的模拟器屏幕上显示12个单元格,所有单元格都被检查。当我开始滚动时,出现的第一个单元格被取消选中,然后是12个选中的单元格:S 当我滚动一下并再次单击“全选”时,跳过的单元格也会被选中..
任何人都有线索我错过了什么?
这是单元代码:
class ListTableViewCell: UITableViewCell {
@IBOutlet weak var checkbox: UIButton!
var buttonState = false{
didSet{
if buttonState{
checkbox.setImage(#imageLiteral(resourceName: "checked"), for: .normal)
}else{
checkbox.setImage(#imageLiteral(resourceName: "unchecked"), for: .normal)
}
}
}
@IBAction func checkboxAction(_ sender: UIButton) {
if buttonState {
buttonState = false
}else{
buttonState = true
}
}
func simulateCheck(){
buttonState = true
}
这里是从我的控制器一些snipets:
private var articleValues: [ArticleValue] = []{
didSet{
tableView.reloadData()
}
}
func selectAll(){
for i in 0..<articleValues.count{
let cell = tableView.cellForRow(at: IndexPath(item: i, section: 0)) as? ListTableViewCell
cell?.simulateCheck()
tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "articleValueItem", for: indexPath)
// Cell Configuration
let articleValue = articleValues[indexPath.row]
if let articleValueCell = cell as? ListTableViewCell{
articleValueCell.articleValue = articleValue
}
return cell
}
为什么不在'articleValues'数组中创建一个属性来检查该项目以及何时重新载入数据(如果在“cellForRowAt”中选中)。不建议直接与单元交互,而是使用数据源。 – GIJOW
我想在你的selectAll()函数中,我会在这个函数的最后调用reloadData()。另外,为什么不在'cellForRowAt'函数中返回'articleValueCell'? – antonio081014
GIJOW大声思考,articleValues连接到数据库,并且我认为将复选框状态保存到数据库不是一个好主意。也许虽然元组或字典可以做到这一点? antonio081014你的第一点是完全正确的性能问题,我想,但我不认为这是问题。你的第二点......我不知道为什么!感谢您指出。 – Thodoris