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

fre*_*dnd 0 uitableview multipleselection ios swift

我花了很多时间寻找解决方案来限制UITableView.

这是我发现的一段代码:

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

    return indexPath
}
Run Code Online (Sandbox Code Playgroud)

问题是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 { $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)
    }
}
Run Code Online (Sandbox Code Playgroud)

解决方案

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
    }
}
Run Code Online (Sandbox Code Playgroud)

Sam*_*Sam 5

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

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
}
Run Code Online (Sandbox Code Playgroud)