您当前将选择状态存储在backgroundColor 中。这不是一个好主意,因为出于性能原因,单元格将被 tableView 重用。
您应该将选定的索引路径保存在数据模型中。如果你想允许多重选择,你可以将选定的索引路径存储在 NSMutableSet 中。
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
cell.selectionStyle = .None
configure(cell, forRowAtIndexPath: indexPath)
return cell
}
var selectedIndexPaths = NSMutableSet()
func configure(cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.textLabel!.text = "Row \(indexPath.row)"
if selectedIndexPaths.containsObject(indexPath) {
// selected
cell.backgroundColor = UIColor.redColor()
}
else {
// not selected
cell.backgroundColor = UIColor.whiteColor()
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if selectedIndexPaths.containsObject(indexPath) {
// deselect
selectedIndexPaths.removeObject(indexPath)
}
else {
// select
selectedIndexPaths.addObject(indexPath)
}
let cell = tableView.cellForRowAtIndexPath(indexPath)!
configure(cell, forRowAtIndexPath: indexPath)
}
如果您只需要单选,您应该将选定的indexPath 保存在NSIndexPath 中吗?实例变量
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
cell.selectionStyle = .None
configure(cell, forRowAtIndexPath: indexPath)
return cell
}
var selectedIndexPath: NSIndexPath?
func configure(cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.textLabel!.text = "Row \(indexPath.row)"
if selectedIndexPath == indexPath {
// selected
cell.backgroundColor = UIColor.redColor()
}
else {
// not selected
cell.backgroundColor = UIColor.whiteColor()
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if selectedIndexPath == indexPath {
// selected same cell -> deselect all
selectedIndexPath = nil
}
else {
// select different cell
let oldSelectedIndexPath = selectedIndexPath
selectedIndexPath = indexPath
// refresh old cell to clear old selection indicators
var previousSelectedCell: UITableViewCell?
if let previousSelectedIndexPath = oldSelectedIndexPath {
if let previousSelectedCell = tableView.cellForRowAtIndexPath(previousSelectedIndexPath) {
configure(previousSelectedCell, forRowAtIndexPath: previousSelectedIndexPath)
}
}
}
let selectedCell = tableView.cellForRowAtIndexPath(indexPath)!
configure(selectedCell, forRowAtIndexPath: indexPath)
}