Ich habe viel Zeit damit verbracht, nach einer Lösung zu suchen, um die Anzahl der ausgewählten Zellen in einem UITableView
zu begrenzen.Anzahl der ausgewählten Zellen nach Abschnitt in TableView beschränken
Hier ist ein Stück Code I gefunden:
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if let selectedRows = tableView.indexPathsForSelectedRows {
if selectedRows.count == limit {
return nil
}
}
return indexPath
}
Das Problem besteht darin, dass tableView.indexPathsForSelectedRows
ausgewählte Zellen enthalten, die sichtbar und von jedem Abschnitt sind.
Gibt es eine Eigenschaft wie: tableView.selectedCellsForSection(section: 0)
?
Danke für Ihre Hilfe!
UPDATE 1
Dies ist ein Beispiel mit einem Auto, das mehr Optionen containts
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)
}
}
SOLUTION
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
}
}
Können Sie nicht einfach von diesem Array filtern? tableView.indexPathsForSelectedRows? .filter ({$ 0.section == section}) – Sam
Können Sie mir bitte erklären, was diese Zeile bedeutet? Ich verstehe nicht '{$ 0.row == Abschnitt}' – fredericdnd
Sorry, es gab einen Tippfehler, sollte {$ 0.section == Abschnitt} sein. In diesem Fall ist Abschnitt Ihre Variable (0 in der Frage). Es zeigt an, dass für jeden indexPath im Array, wenn der Abschnitt der gleiche wie der variable Abschnitt ist, sollte – Sam