在 TableView 中按部分限制所选单元格的数量

Limit number of selected cells by section in TableView

我花了很多时间寻找解决方案来限制 UITableView 中选定单元格的数量。

这是我找到的一段代码:

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    if let selectedRows = tableView.indexPathsForSelectedRows {
        if selectedRows.count == limit {
            return nil
        }
    }

    return indexPath
}

问题是 tableView.indexPathsForSelectedRows 包含来自任何部分的可见的选定单元格。

属性 是否存在:tableView.selectedCellsForSection(section: 0)

感谢您的帮助!

更新 1

这是一个包含多个选项的汽车示例

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 { [=11=].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
    }
}

这会将其限制在单击该行的部分:

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    if let selectedRows = tableView.indexPathsForSelectedRows?.filter({ [=10=].section == indexPath.section }) {
        if selectedRows.count == limit {
            return nil
        }
    }

    return indexPath
}