And*_*rin 2 uitableview ios swift
使用以下代码,当我单击一个单元格以创建一个复选标记附件时,它会每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
}
Run Code Online (Sandbox Code Playgroud)
当Cell对象被重用时,您不能依赖它们来存储数据或状态.它们只是您对数据模型中的数据的查看.您需要重置已检查/未检查状态cellForRowAtIndexPath
用于记录小区选择状态的一种技术是使用a 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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1525 次 |
| 最近记录: |