1

I am trying to achieve to make my TableView only accept one checkbox per cell.

I have used this solution to save User Defaults for the checkmarks which works fine but it allow multiple selections.

I have tried so many solutions on Stack overflow but since this is formatted a little different I was unable to use those solutions.

Things I have tried which did not work:

Tried setting the accessory type to none at the didDeselectRowAt

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
   tableView.cellForRow(at: indexPath)?.accessoryType = .none 
}

Tried setting the table view to not allow multiple selections on the viewDidNotLoad

override func viewDidLoad()
{
    tableViewName.allowsMultipleSelection = false
}

Based the solution I linked, how would I go to only allow a single selection?

Nick
  • 875
  • 6
  • 20
Broski
  • 75
  • 9

1 Answers1

1

In the solution you have linked there is this code in the 'didSelect' function

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
{
    if selectedRows.contains(indexPath.row) {
        self.selectedRows = selectedRows.filter{$0 != indexPath.row}
    }else{
        self.selectedRows.append(indexPath.row)
    }
    UserDefaults.standard.set(selectedRows, forKey: "selectedRows")
}

If you only want a single checkbox to be selected then you only want a single entity saved in your selectedRows object. Change the above code to:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
{
    self.selectedRows = [indexPath.row]

    UserDefaults.standard.set(selectedRows, forKey: "selectedRows")
}

Then every time a checkbox is selected it will clear out all the other selected checkboxes and select only the checkbox you just clicked.

Putz1103
  • 6,211
  • 1
  • 18
  • 25