How to deselect selected cell in UITableView - ios

Normally, when I touch UITableViewCell, then UITableViewCell is selected and highlighted.
But, again touch exactly same UITableViewCell, then nothing happen.
I want that if I touch selected UITableViewCell, then UITableVIewCell to deselect.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) else { return }
if cell.isSelected == true {
cell.isSelected = false
}
}
/////
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) else { return }
if cell.isSelected == false {
cell.isSelected = true
} else {
cell.isSelected = false
}
}
Both source code does not working. How do I fix this method?

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

Related

Swift UITableview cell checkmark with selection blink option

My scenario, I am trying to create UITableview single cell checkmark selection and Multiple cell check mark selection. Here, I am trying by below code for single selection check mark but Its reusability not working. Also, I don't know how to do multiple cell selection by clicking cell section.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
For reusability, you need a variable to save the selected cell index(or array for cells) and then set the appropriate accessoryType when displaying the cell.
For single selection, remember to clear the previous selection.
A sample pattern for single selection:
var selectedRow = 0
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedRow = indexPath.row
for cell in tableView.visibleCells { //Why not using didDeselectRowAt? Because the default selected row(like row 0)'s checkmark will NOT be removed when clicking another row at very beginning.
cell.accessoryType = .none
}
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.accessoryType = indexPath.row == selectedRow ? .checkmark : .none
}
A pattern for multiple selections (Updated for multi-sections):
var selectedIndexPaths = Set<IndexPath>()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if selectedIndexPaths.contains(indexPath) { //deselect
selectedIndexPaths.remove(indexPath)
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
else{
selectedIndexPaths.insert(indexPath) //select
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.accessoryType = selectedIndexPaths.contains(indexPath) ? .checkmark : .none
}
Model
class Item {
var name:String!
var isSelected = false
}
then inside cellForRowAt
cell.accessoryType = items[indexPath.row].isSelected ? .checkmark : .none
inside didSelectRowAt
items[indexPath.row].isSelected.toggle()
tableView.reloadRows(at:[indexPath],with:.none)
Set isSingleSelection to false for multiple selections and to true for single selection
var isCellSelected = [Bool]()
var isSingleSelection = false
override func viewDidLoad() {
super.viewDidLoad()
for _ in arrayFillingYourTableview { isCellSelected.append(false) }
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = branchTbView.dequeueReusableCell(withIdentifier: "cell")!
cell.accessoryType = isCellSelected[indexPath.row] ? .checkmark : .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if isSingleSelection {
for i in 0..<isBranchSelected.count {
isCellSelected[i] = false
}
}
isCellSelected[indexPath.row] = ! isCellSelected[indexPath.row]
tableView.reloadData()
}
}

How can we deselect the row when we Off the switch

I have a tableview. In the tableview cell I have a label and switch. Here I want to deselect the row when switch is off.
Here is my code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! BM_MyBusinessTableViewCell
cell.tapSwitch.tag = indexPath.row
cell.businessLabel.text = labelArray[indexPath.row]
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
Don't select/deselect the cell when the switch is tapped. Just store the indexPath.row of the selected switches and reload the tableview.
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
let labelArray = ["Employees", "Break Time Setup", "Employee Timeoff", "Reports", "Messages"]
var selectedIndexPaths = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return labelArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! Cell
cell.selectionStyle = .none
cell.tapSwitch.isOn = selectedIndexPaths.contains(indexPath.row)
cell.tapSwitch.tag = indexPath.row
cell.tapSwitch.addTarget(self, action: #selector(tapSwitchAction(_:)), for: .valueChanged)
cell.businessLabel.text = labelArray[indexPath.row]
return cell
}
#objc func tapSwitchAction(_ sender: UISwitch) {
if sender.isOn {
selectedIndexPaths.append(sender.tag)
} else {
selectedIndexPaths.removeAll { $0 == sender.tag }
}
tableView.reloadData()
}
}
Then you can get the selected row values anywhere like this
#objc func getSelectedValues() {
let selectedLabelArray = labelArray.enumerated().filter { selectedIndexPaths.contains($0.offset) }
print(selectedLabelArray)
}
Update
Option 1
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if selectedIndexPaths.contains(indexPath.row) {
selectedIndexPaths.removeAll { $0 == indexPath.row }
} else {
selectedIndexPaths.append(indexPath.row)
}
tableView.reloadData()
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
//do nothing
}
Option 2
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? BM_MyBusinessTableViewCell {
cell.tapSwitch.isOn = !cell.tapSwitch.isOn
tapSwitchAction(cell.tapSwitch)
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? BM_MyBusinessTableViewCell {
cell.tapSwitch.isOn = !cell.tapSwitch.isOn
tapSwitchAction(cell.tapSwitch)
}
}

TableView CheckMark and Uncheck With Scroll Up Still Checked Cell Value In Ios Swift 4

TableView CheckMark Cell Value Removed After Scrolling Up It will Fix
TableView in You have face a problem many times to Checkmark after scroll Up then Scroll Down To show a Your Checkmark cell is will Removed Because cell is dequeueReusableCell So This Problem Fix , you Have just put Your code and Solved Your Problem.
Any More Help So Send Massage.
Thank you So much. :)
class ViewController: UIViewController , UITableViewDataSource , UITableViewDelegate{
var temp = [Int]()
var numarr = [Int]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numarr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "id")
cell = UITableViewCell.init(style: .default, reuseIdentifier: "id")
cell?.textLabel?.text = String(numarr[indexPath.row])
if temp.contains(numarr[indexPath.row] as Int)
{
cell?.accessoryType = .checkmark
}
else
{
cell?.accessoryType = .none
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if temp.contains(numarr[indexPath.row] as Int)
{
cell?.accessoryType = .none
temp.remove(at: temp.index(of: numarr[indexPath.row])!)
}
else
{
cell?.accessoryType = .checkmark
temp.append(self.numarr[indexPath.row] as Int)
}
}
override func viewDidLoad() {
super.viewDidLoad()
for i in 1...100
{
numarr.append(i)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
I think if someone were to run your code it would not show any error. But with real data it probably will. The reason is the way you store your checkmarks. You store the data of a row into the temp array when you should be storing the actualy indexPath of the array so that only that row gets the checkmark. In your case, if a row has 1 inside it's label and you click on it, that cell will be highlighted. Now if you start scrolling and another cell contains 1 then that row will also be highlighted.
I have modified your example for the case of a single section. If there is more than one section, you need to store the indexPath instead of indexPath.row.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "id")
cell = UITableViewCell.init(style: .default, reuseIdentifier: "id")
cell?.textLabel?.text = String(numarr[indexPath.row])
if temp.contains(indexPath.row) {
cell?.accessoryType = .checkmark
} else {
cell?.accessoryType = .none
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if temp.contains(indexPath.row) {
cell?.accessoryType = .none
temp.remove(at: indexPath.row)
} else {
cell?.accessoryType = .checkmark
temp.append(indexPath.row)
}
}
You are strongly discouraged from using a second array to keep the selected state.
This is Swift, an object oriented language. Use a custom struct for both num and the selected state.
In didSelectRowAt and didDeselectRowAt change the value of isSelected and reload the row.
And use always the dequeueReusableCell API which returns a non-optional cell.
struct Item {
let num : Int
var isSelected : Bool
}
var numarr = [Item]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numarr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "id", for: indexPath)
let item = numarr[indexPath.row]
cell.textLabel?.text = String(item)
cell.accessoryType = item.isSelected ? .checkmark : .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
updateSelection(at: indexPath, value : true)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
updateSelection(at: indexPath, value : false)
}
func updateSelection(at indexPath: IndexPath, value : Bool) {
let item = numarr[indexPath.row]
item.isSelected = value
tableView.reloadRows(at: [indexPath], with: .none)
}
override func viewDidLoad() {
super.viewDidLoad()
(0...100).map{Item(num: $0, isSelected: false)}
}

Limit number of selected cells by section in TableView

I've spent a lot of time searching a solution to limit the number of selected cells in a UITableView.
Here is a piece of code I found :
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if let selectedRows = tableView.indexPathsForSelectedRows {
if selectedRows.count == limit {
return nil
}
}
return indexPath
}
The problem is that tableView.indexPathsForSelectedRows contains selected cells that are VISIBLE and from any section.
Does a property like : tableView.selectedCellsForSection(section: 0) exist ?
Thanks for your help !
UPDATE 1
This is an example with a car that containts several options
var selectedOptions = [IndexPath : Option]() // Option can be for example, the color of the car
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let maxOptionForSection = car.options![indexPath.section]?.max
let numberOfSelectedOptions = selectedOptions.filter { $0.key.section == indexPath.section }
if numberOfSelectedOptions.count == maxOptionForSection {
return nil
}
return indexPath
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? OptionCell {
cell.checkButton.isChecked = true
cell.option.isSelected = true
selectedOptions[indexPath] = cell.option
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? OptionCell {
cell.checkButton.isChecked = false
cell.option.isSelected = false
selectedOptions.removeValue(forKey: indexPath)
}
}
SOLUTION
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let optionCell = cell as! OptionCell
if optionCell.option.isSelected {
optionCell.checkButton.isChecked = true
} else {
optionCell.checkButton.isChecked = false
}
}
This will limit it to the section in which the row was clicked:
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if let selectedRows = tableView.indexPathsForSelectedRows?.filter({ $0.section == indexPath.section }) {
if selectedRows.count == limit {
return nil
}
}
return indexPath
}

UITableViewCell checkmark to be toggled on and off when tapped

I'm working on a tableview
I want to be able to tap on each cell and when tapped, it displays a checkmark on the cell
Now I have some code that makes this work:
// checkmarks when tapped
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let section = indexPath.section
let numberOfRows = tableView.numberOfRowsInSection(section)
for row in 0..<numberOfRows {
if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) {
cell.accessoryType = row == indexPath.row ? .Checkmark : .None
}
}
}
but this code only selects 1 cell inside a section (I have 5 sections)
I need it to select any cell anywhere
Also when I drag my screen up and down I lose by checkmark
viewcontroller.swift
class ViewController: UIViewController, UITableViewDataSource { //class and subclass |)
//---------------------------------------------------------------------------------------------------------------------------/
// Variable and constant, also IBAOutlet
let section1 =
["this is used",
"this is used to test",
"this is used to test the lenght",
"this is used to test the lenght of the text",
"this is used to test the lenght of the text",
"this is used to test the lenght of the text",
"this is used to test the lenght of the text",
"this is used to test the lenght of the text",
"this is used to test the lenght of the text",]
let section2 =
["this is used to test the lenght of the text"]
let section3 =
["this is",
"this is ",]
#IBOutlet weak var scoreshow: UILabel!
#IBOutlet weak var reset: UIButton!
#IBOutlet weak var tableView: UITableView!
// --------------------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//----------------------------------------------------------------------------------------
// checkmarks when tapped
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
if cell.accessoryType == .Checkmark
{
cell.accessoryType = .None
}
else
{
cell.accessoryType = .Checkmark
}
}
}
//----------------------------------------------------------------------------------------
//number of sections for the table
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 5
}
//----------------------------------------------------------------------------------------
//Calculate the amount of rows
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.section1.count;
}
//----------------------------------------------------------------------------------------
//Cells text label and config
func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell")
cell.textLabel!.text = section1[indexPath.row]
cell.textLabel!.numberOfLines = 0
return cell
}
//----------------------------------------------------------------------------------------
#IBAction func resetswitch(sender: UIButton) {
}
//----------------------------------------------------------------------------------------
}
Swift > 3.0
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .none
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark
}
}
I solved by using two Swift functions: the didSelectRowAtIndexPath and the didDeselectRowAtIndexPath.
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.accessoryType = .None
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.accessoryType = .Checkmark
}
}
To make this work properly, add a line of code to your cellForRowAtIndexPath function to select a row when the table view is drawn on the screen, otherwise the didDeselectRowAtIndexPath will not be called the first time you select another row. Like so:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellData", forIndexPath: indexPath)
if (some condition to initially checkmark a row)
cell.accessoryType = .Checkmark
tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.Bottom)
} else {
cell.accessoryType = .None
}
return cell
}
Try this:
var checked = [Bool]() // Have an array equal to the number of cells in your table
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
//configure you cell here.
if !checked[indexPath.row] {
cell.accessoryType = .None
} else if checked[indexPath.row] {
cell.accessoryType = .Checkmark
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
if cell.accessoryType == .Checkmark {
cell.accessoryType = .None
checked[indexPath.row] = false
} else {
cell.accessoryType = .Checkmark
checked[indexPath.row] = true
}
}
}
To reset all the checkboxes:
func resetChecks() {
for i in 0.. < tableView.numberOfSections {
for j in 0.. < tableView.numberOfRowsInSection(i) {
if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: j, inSection: i)) {
cell.accessoryType = .None
}
}
}
}
A UITableView keeps selected state for single or multiple selections. So IMO there would need to be a very good reason for keeping an entire parallel state somewhere. If you want to just change the cell's appearance based on select state, do it in the cell.
In your UITableViewCell subclass, override setSelected like so:
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
self.accessoryType = selected ? .checkmark : .none
}
No need to use any table view delegate methods.
Note: You have to call super.setSelected otherwise the cell doesn't keep the selected state correctly.
Swift 3.0
Using just one function to keep it simple
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
if cell.accessoryType == .checkmark {
cell.accessoryType = .none
} else {
cell.accessoryType = .checkmark
}
}
}
Swift 3.0
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .none
}
}
Swift 4.0, all together now:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var yourData = ["Cool","Sweet","Awesome"]
var checked = [Bool]()
override func viewDidLoad() {
super.viewDidLoad()
checked = Array(repeating: false, count: yourData.count)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchData.count
}
func tableView(_ tableView: UITableView, cellForRowAt IndexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
//configure you cell here.
if checked[IndexPath.row] == false{
cell.accessoryType = .none
} else if checked[IndexPath.row] {
cell.accessoryType = .checkmark
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
if cell.accessoryType == .checkmark {
cell.accessoryType = .none
checked[indexPath.row] = false
} else {
cell.accessoryType = .checkmark
checked[indexPath.row] = true
}
}
}
}
Swift 5.0
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let cell = tableView.cellForRow(at: indexPath) {
resetChecks()
cell.accessoryType = .checkmark
}
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
self.tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
func resetChecks() {
for i in 0..<tableView.numberOfSections {
for j in 0..<tableView.numberOfRows(inSection: i) {
if let cell = tableView.cellForRow(at: IndexPath(row: j, section: i)) {
cell.accessoryType = .none
}
}
}
}
The simple solution as others have pointed out would be to .checkmark the row in the didSelectRowAt method and set the row to .none in the didDeselectRowAtmethod as follow...
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
But if you have a default row selected when the table loads you first need to deselect it when other rows are selected, in that case, use the code below instead in the didSelectRowAt method.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
for row in 0..<tableView.numberOfRows(inSection: indexPath.section) {
if let cell = tableView.cellForRow(at: IndexPath(row: row, section: indexPath.section)) {
cell.accessoryType = row == indexPath.row ? .checkmark : .none
}
}
}
Updated In swift 4.2
Every New selection Remove previous Check mark
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(self.coloursArray[indexPath.row])
self.tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
self.tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
For Swift 5:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
cell.accessoryType = .checkmark
}
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
cell.accessoryType = .none
}
}
The simplest solution that did it for me (Swift 5.2)
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
// Remove checkmark from the row that is currently showing it before adding to one being selected
if let currentIndexPath = tableView.indexPathForSelectedRow {
self.tableView.cellForRow(at: currentIndexPath)?.accessoryType = .none
}
return indexPath
}
override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
For anyone using a single use of a checkmark.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// checkmark logic
if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
if cell.accessoryType != .checkmark {
resetChecks()
cell.accessoryType = .checkmark
}
}
}
func resetChecks() {
for i in 0..<tableView.numberOfSections {
for j in 0..<tableView.numberOfRows(inSection: i) {
if let cell = tableView.cellForRow(at: NSIndexPath(row: j, section: i) as IndexPath) {
cell.accessoryType = .none
}
}
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if self.checkedIndex == indexPath.row{
}else{
let cell = tableView.cellForRow(at: indexPath)
cell?.accessoryType = .checkmark
let indexPathh = IndexPath(row: checkedIndex, section: 0)
let UnCheckCell = tableView.cellForRow(at: indexPathh)
UnCheckCell?.accessoryType = .none
checkedIndex = indexPath.row
}
}
Since I didn't see anyone list this, you can create a custom UITableViewCell that will toggle the checkmark with selection by overriding it's setSelected() method and defaulting .selectionStyle to .gray:
class CheckableTableViewCell: UITableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .gray
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
accessoryType = selected ? .checkmark : .none
}
}
I have used tableView(_:didSelectRowAt:), delegate method to accomplish this feature of putting check mark on the cell and removing it when the cell is tapped again.
Here is the code:
//MARK:-create delegate methode that is fired when a cell is clicked
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath , animated: true)
if let cell = tableView.cellForRow(at: indexPath){
if cell.accessoryType == .checkmark {
cell.accessoryType = .none
}
else {
cell.accessoryType = .checkmark
}
}
}

Resources