How to Deselect a Selected Uitableview Cell

How to deselect selected cell in UITableView

Minimal working example (first 7 cells are selectable):

import UIKit
import PlaygroundSupport

class MyTableViewController: UITableViewController {

var selectedIndexPath: IndexPath? = nil

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 7
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell()
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if selectedIndexPath == indexPath {
// it was already selected
selectedIndexPath = nil
tableView.deselectRow(at: indexPath, animated: false)
} else {
// wasn't yet selected, so let's remember it
selectedIndexPath = indexPath
}
}
}

// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyTableViewController()

UITableView selected cell not getting deselect

I have resolved this issue the problem was related to the way I was setting the cell selection I have added the following line in the cellForRow method.

    if cellItem.isSelected {
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
} else {
tableView.deselectRow(at: indexPath, animated: true)
}

How to deselect UITableView cell when user click to button?

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)
}
}
}

How to deselect tableview cell when selecting another tableview cell in the meantime?

Instead of calling setSelected:animated: on the cell directly, call the selectRowAtIndexPath:animated:scrollPosition: method of the table view to set the initial selection.

Facing issue in selecting and deselecting tableview cell in swift

For issue 1 - By using this line of code:

var pincodePreviousIndex: Int = 0

You cannot click the first row until you click another since

pincodes[pincodePreviousIndex].isSelected = false

Since you're defaulting to 0 in the beginning, that correlates to the first row.

For issue 2 - if you select row 2 (selected) and then select it again to deselect it: pincodePreviousIndex will hold the value of that row and then deselect it again with

pincodes[pincodePreviousIndex].isSelected = false

So even though you're selecting it it will deselect it.

I would do this at the top:
var pincodePreviousIndex: Int = -1

and at the bottom:

if pincodePreviousIndex > 0 && pincodePreviousIndex != indexPath.row {
pincodes[pincodePreviousIndex].isSelected = false
}


Related Topics



Leave a reply



Submit