How to make checkmark single selection to Each Section , with custom cells , when I realize this code , cell doesn't marked
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let it = PayMentSection(rawValue: indexPath.section) else {return}
switch it {
case .delivering:
let cell = tableView.dequeueReusableCell(withIdentifier: cellid) as! MakePaymentTableViewCell
cell.checkBox.isChecked = true
cell.accessoryType = .checkmark
case .ordering:
let cell2 = tableView.dequeueReusableCell(withIdentifier: cellid2) as! MakePaymentTableViewCell2
cell2.checkBox.isChecked = true
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
guard let it = PayMentSection(rawValue: indexPath.section) else {return}
switch it {
case .delivering:
let cell = tableView.dequeueReusableCell(withIdentifier: cellid) as! MakePaymentTableViewCell
cell.checkBox.isChecked = false
cell.accessoryType = .none
case .ordering:
let cell2 = tableView.dequeueReusableCell(withIdentifier: cellid2) as! MakePaymentTableViewCell2
cell2.checkBox.isChecked = false
cell2.accessoryType = .none
}
}
First of all, implement UITableViewDelegate's
tableView(_:willSelectRowAt:)
method like so,
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if let selectedIndexPathsInSection = tableView.indexPathsForSelectedRows?.filter({ $0.section == indexPath.section }), !selectedIndexPathsInSection.isEmpty {
selectedIndexPathsInSection.forEach({ tableView.deselectRow(at: $0, animated: false) })
}
return indexPath
}
Next, in both MakePaymentTableViewCell
and MakePaymentTableViewCell2
cells, override setSelected(_:animated:)
method, i.e.
class MakePaymentTableViewCell: UITableViewCell {
//rest of the code...
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
self.accessoryType = selected ? .checkmark : .none
self.checkBox.isChecked = selected
}
}
There is no need to implement didSelectRowAt
and didDeselectRowAt
methods.