ios
ios

Reputation: 975

Set Selected/ Unselected view color in UITableView in Swift

I have a tableview with which all views will be of clear colour. When user selected a cell I need to make selected tableview cell red and reset all other previous cells to clear colour. How can I manage state of the cell whether it is selected or not.

I am using this code to change the color of selected index.

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    guard let cell:TableViewCell = tableView.cellForRow(at: indexPath) as?  TableViewCell else { return }
    cell.backgroundColor = UIColor.red
}

I am not able to reset the previous cell.

Upvotes: 0

Views: 1767

Answers (3)

vadian
vadian

Reputation: 285074

Based on PGDev's answer you need a property in the view controller to keep the selected index path

var selectedIndexPath : IndexPath?

If no row is selected the property is nil


In cellForRow add a line to manage the selection

cell.isSelected = indexPath == selectedIndexPath

In didSelectRowAt compare the just selected index path with selectedIndexPath, update selectedIndexPath and reload the rows accordingly.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var pathsToReload = [indexPath]
    if let selectedPath = selectedIndexPath {
        if indexPath == selectedPath { // deselect current row
            selectedIndexPath == nil
        } else { // deselect previous row, select current row
            pathsToReload.append(selectedPath)
            selectedIndexPath = indexPath
        }
    } else { // select current row
        selectedIndexPath == indexPath
    }
    tableView.reloadRows(at: pathsToReload, with: .automatic)
}

Upvotes: 1

Picode
Picode

Reputation: 1158

You can use deselectRow func of tableView :

func deselectRow(at indexPath: IndexPath, 
    animated: Bool){
    guard let cell:TableViewCell = tableView.cellForRow(at: indexPath) as?  TableViewCell else { return }
cell.backgroundColor = UIColor.clear
}

Hope it helps...

Upvotes: 1

PGDev
PGDev

Reputation: 24341

You need to override setSelected(_:animated:) method in TableViewCell and configure the backgroundColor based on selected state.

class TableViewCell: UITableViewCell {
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        self.backgroundColor = selected ? .red : .clear
    }
}

No need to change the backgroundColor in tableView(_:didSelectRowAt:) method.

Upvotes: 4

Related Questions