我有一个包含多个部分的表格视图,每个部分都有 3 个单元格,每个单元格包含自定义复选标记按钮。用户可以在单击时更改检查和取消选中检查按钮的图像。 问题是,我正在将单元格按钮图像从取消选中更改为在用户单击按钮时检查,该按钮工作正常。如果我滚动表格视图,复选标记图像正在添加到错误的单元格。
我用谷歌搜索了它,找到了解决方案,例如将单击的单元格 indexPath.row 保存在数组中,并在用户再次单击同一单元格时从数组中删除。 它不起作用,因为我有多个部分。
请为我提供任何建议,以找出我的问题的解决方案。
// Button action.
func buttonTappedOnCell(cell: customeCell) {
let indexPath : IndexPath = self.tableView.indexPath(for: cell)!
if self.selectedIndexPath.count > 0 {
for selectedIndex in self.selectedIndexPath {
if selectedIndex as! IndexPath == indexPath {
self.selectedIndexPath.remove(indexPath)
} else {
self.selectedIndexPath.add(indexPath)
}
}
} else {
self.selectedIndexPath.add(indexPath)
}
cellForRowAtIndexPath 中的代码
for anIndex in self.selectedIndexPath {
if anIndex as! IndexPath == indexPath {
cell.checkMarkButton.setBackgroundImage(UIImage(named: "checkMark"), for: .normal)
} else {
cell.checkMarkButton.setBackgroundImage(UIImage(named: "UnCheckMark"), for: .normal)
}
}
您可以使用Set<IndexPath>
大大简化代码。 无需遍历数组。
var selectedPaths=Set<IndexPath>()
func buttonTappedOnCell(cell: customeCell) {
if let indexPath = self.tableView.indexPath(for: cell) {
var image = UIImage(named: "CheckMark")
if self.selectedPaths.contains(indexPath) {
image = UIImage(named: "UnCheckMark")
self.selectedPaths.remove(indexPath)
} else {
self.selectedPaths.insert(indexPath)
}
cell.checkMarkButton.setBackgroundImage(image, for: .normal)
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as! YourCellType
...
var image = UIImage(named: "UnCheckMark")
if self.selectedPaths.contains(indexPath) {
image = UIImage(named: "checkMark")
}
cell.checkMarkButton.setBackgroundImage(image, for: .normal)
return cell
}
发生这种情况是因为重复使用表视图的单元格以最大程度地减少内存使用量。
如果您使用的是check button
custom implementation
,则必须存储data Structure like an array
中选择的单元格的值,例如,如果您有 2 个部分,每个部分有 3 个元素,并且第 1 部分中的第 2 个项目被选中,那么像数组一样的数据结构可以像[[false, true, false], [false, false. false]]
一样。 在这里,如果选择了单元格,我将设置为 true。更新此数据结构的值,并在cellForRowAt
中应用图像时对其进行检查,并且仅当数组的 indexPath.section 和 indexPath.row 返回true
布尔值时,才应用 checkedImage。
希望这有帮助。如有任何疑问,请随时与我们联系。快乐编码。
在你的TableView DidSelect方法里面,只是把
let cell = tableView.cellForRowAtIndex(indexPath).accessoryType = UITableViewCell.accessoryType = Checkmark
反之亦然,对于 DidDeselect 方法,但将复选标记更改为无。
let cell = tableView.cellForRowAtIndex(indexPath).accessoryType = UITableViewCell.accessoryType = None
如果你为一个简单的方法创建更复杂的代码,它会给你带来灾难。