使用以下代码,当我单击一个单元格以创建复选标记配件时,它会每 12 行重复复选标记。关于原因有什么想法吗?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? UITableViewCell
cell?.textLabel = "\(indexPath.row)"
return cell!
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? UITableViewCell {
if cell.accessoryType == UITableViewCellAccessoryType.Checkmark
{
cell.accessoryType = UITableViewCellAccessoryType.None
}
else
{
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
}
}
return indexPath
}
最佳答案
由于 Cell 对象被重复使用,您不能依赖它们来存储数据或状态。它们只是对数据模型中数据的看法。您需要在 cellForRowAtIndexPath
记录单元格选择状态的一种技术是使用Set
来存储所选的indexPaths
。这是一个简单的例子,展示了这种技术 -
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var checkedRows=Set<NSIndexPath>()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100 // Simple example - 100 fixed rows
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell=tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as!UITableViewCell
cell.textLabel!.text="Row \(indexPath.row)"
cell.accessoryType=self.accessoryForIndexPath(indexPath)
return cell
}
func accessoryForIndexPath(indexPath: NSIndexPath) -> UITableViewCellAccessoryType {
var accessory = UITableViewCellAccessoryType.None
if self.checkedRows.contains(indexPath) {
accessory=UITableViewCellAccessoryType.Checkmark
}
return accessory
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if checkedRows.contains(indexPath) {
self.checkedRows.remove(indexPath)
} else {
self.checkedRows.insert(indexPath)
}
if let cell=tableView.cellForRowAtIndexPath(indexPath) {
cell.accessoryType=self.accessoryForIndexPath(indexPath)
}
}
}
关于ios - UITableViewCell 快速重复每 12 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31820033/