How can I do to limit the selection of row in tableview to 2.
I mean I have a tableview with items but the user can select unlimited rows. I want to set to 2 selected row maximum.
I just made a listeSiropsSelected and put items on it, and if this list .count >= 2, display an alert. But the 3rd row is selected even if alert is show.
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("Tableview setup (listeSirops.count) items")
return listeSirops.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "siropCell", for: indexPath) as? ChoisirSiropTableViewCell else {
fatalError("Unable to dequeue tabacCell")
}
let tabac = listeSirops[indexPath.row]
cell.labelNom.text = tabac.nom
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let sirops = listeSirops[indexPath.row]
if(listeSiropsSelected.count >= 2) {
let alert = UIAlertController(title: "Erreur", message: "Vous ne pouvez choisir que 2 sirops.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
}))
self.present(alert, animated: true, completion: nil)
} else {
listeSiropsSelected.append(sirops.nom)
print(listeSiropsSelected)
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let sirops = listeSirops[indexPath.row]
let objectToRemove = sirops.nom
listeSiropsSelected.remove(object: objectToRemove)
print(listeSiropsSelected)
}
3 rows selected, message appear but how can remove the 3rd row ?
3
Answers
Just add this line under
self.present
:Implement
willSelectRowAt
, it prevents the selection of a cell ifnil
is returnedDelete the alert, it’s not needed, the user experience is that the user is not able to select more than 2 cells.