ava ava - 2 months ago 7
Swift Question

Store TableView selected Row

I have a table view, I want to change selected table view selected cell color, and cell color not changed when scroll table view. there is my code:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath
indexPath: NSIndexPath) {
let selectCell = tableView.indexPathForSelectedRow
self.selectedCell.append(selectCell!)
for i in selectedCell
{
if(!(i .isEqual(indexPath)))
{
let currentCell = tableView.cellForRowAtIndexPath(i)! as UITableViewCell

currentCell.backgroundColor = UIColor.lightGrayColor()
}
}


that's code crash when scroll table view.

Answer

Your code seems very strange to me. you don't need to set the background color of all other cells each time one is selected. Define your celectedCells as dictionary of type Int:Bool so you can set it to true for each indexpath.row like this:

var selectedCells = [Int: Bool]()

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if let cell = tableView.cellForRowAtIndexPath(indexPath) {
        cell.backgroundColor = UIColor.lightGrayColor()
        selectedCells[indexPath.row] = true
    }
}

and then in your cellForRowAtIndexPath method check that dictionary to set the backgroundColor, like this:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("YourCellIdentifier", forIndexPath: indexPath)

    if selectedCells[indexPath.row] == true {
        // Color for selected cells
        cell.backgroundColor = UIColor.lightGrayColor()
    } else {
        // Color for not selected cells
        cell.backgroundColor = UIColor.whiteColor()
    }
    //Rest of your Cell setup

    return cell
}
Comments