s.satcha
s.satcha

Reputation: 23

How to deselect UITableView cell when user click to button?

I am working on a project in which I have to select a particular cell. I can select a cell in my UITableView, but I want to deselect all cells when the user clicks on Button -RESET-< I mean button action> so I don't know how I can do it. I need help, please.

My code to select a cell:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //changer la couleur de la cellule à la selection
    let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath as IndexPath)!
    selectedCell.contentView.backgroundColor = UIColor.darkGray

    if !Array( addObject.dictionnary.values)[indexPath.row] {
        addObject.dictionnary[Array( addObject.dictionnary.keys)[indexPath.row]] = true
    } else {
        addObject.dictionnary[Array( addObject.dictionnary.keys)[indexPath.row]] = false
    }
    tableView.reloadData()
}

Upvotes: 0

Views: 4543

Answers (3)

app4g
app4g

Reputation: 850

I was looking for this and found some docs from Apple at Link to Apple Docs but it showed to put the call at ViewWillAppear. Xcode didn't like it, so after more research, finally found that this is the place to put it

tableView.deselectRow(at: indexPath, animated: true)

within the

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

Upvotes: 0

Austin
Austin

Reputation: 64

Here is a quick code snippet that might lead you in the correct direction.

@IBAction func onResetButtonTouchUpInside(sender: AnyObject) {
     if let selectedIndexPaths = tableView.indexPathsForSelectedRows {
          for indexPath in selectedIndexPaths {
                tableView.deselectRow(at: indexPath, animated: true)
          }
     }
}

Upvotes: 4

Mohammad Sadiq
Mohammad Sadiq

Reputation: 5241

You can use

 tableView.deselectRow(at: tableView.indexPathForSelectedRow!, animated: true)

Upvotes: 0

Related Questions