Search code examples
iosxcodeswiftuitableviewdidselectrowatindexpath

Tableviewcell should know if it is selected on app load in - iOS swift


i build a switch with false and true values, when ever i select a cell in my tableview. That works fine now. But on app load the cell doesn't know it has been selected before. I am changing the cell on load, depending on the saved switch data, so it looks like it is a selected cell. When i click the cell. It behaves like i am pressing it for the first time. So it does not use deselect function first. And starts again with selecting the cell, which is not nice for the user. I tried to use setSelected on true. But that didn't do the trick for me.

I guess i am missing something here... Any help is appreciated thx :)

if boolTest?.boolValue == true {
        println("its true")
        cell.accessoryType = UITableViewCellAccessoryType.Checkmark
        cell.tintColor = UIColor(red:0.13, green:0.13, blue:0.13, alpha:1)
    }
    else {
        println("its false")
        cell.accessoryType = UITableViewCellAccessoryType.None
    }

Solution

  • You shouldn't try to set the cell's selected state itself by calling setSelected. The tableView maintains its own set of selected indexPaths, so proper rows will remain selected as cells are reused.

    The distinction matters because there's a difference between a cell appearing to be selected, as you're trying to achieve, compared to the tableView knowing whether or not an indexPath is selected when the tableView prepares to display the cell's (selected) appearance.

    If you want the cell to merely appear to be selected, you can call setSelected in willDisplayCell.

    If you want the tableView to know the cell is selected, so it can handle deselecting a selected cell for you, use selectRowAtIndexPath.