如何使用自定义单元格对每个部分进行复选标记单选,当我实现此代码时,单元格未标记
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
}
}
首先,像这样实现
UITableViewDelegate's
tableView(_:willSelectRowAt:)
方法,
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
}
接下来,在
MakePaymentTableViewCell
和 MakePaymentTableViewCell2
单元格中,重写 setSelected(_:animated:)
方法,即
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
}
}
无需实现
didSelectRowAt
和 didDeselectRowAt
方法。
你可以试试这个方法
创建变量作为 IndexPath 类型(就像你有 3 个部分创建 3 个变量)
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 0:
if let previousIndexPath = selectedValueIndexPath {
tableView.cellForRow(at: previousIndexPath)?.accessoryType = .none
}
selectedValueIndexPath = indexPath
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
case 1:
if let previousIndexPath = selectedOrderIndexPath {
tableView.cellForRow(at: previousIndexPath)?.accessoryType = .none
}
selectedOrderIndexPath = indexPath
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
default:
break
}
}