在 TableView 中按部分限制所选单元格的数量 [英] Limit number of selected cells by section in TableView
本文介绍了在 TableView 中按部分限制所选单元格的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我花了很多时间寻找解决方案来限制 UITableView
中所选单元格的数量.
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
}
问题在于 tableView.indexPathsForSelectedRows
包含可见且来自任何部分的选定单元格.
The problem is that tableView.indexPathsForSelectedRows
contains selected cells that are VISIBLE and from any section.
是否存在像:tableView.selectedCellsForSection(section: 0)
这样的属性?
Does a property like : tableView.selectedCellsForSection(section: 0)
exist ?
感谢您的帮助!
更新 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)
}
}
解决方案
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
}
这篇关于在 TableView 中按部分限制所选单元格的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文