You are currently saving the selection state in backgroundColor. This is not a good idea, because for performance reasons the cells will reuse the tableView.
You must save the selected indexPaths in the data model. If you want to enable multiple selections, you can save the selected indexes to an 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) {
If you need only one choice, you have to save the selected indexPath to NSIndexPath? instance variable
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) }
Matthias bauch
source share