我有一个AllowsMultipleSelection = True的TableView,允许用户选择任意数量的行。我希望我的 TableView 至少选择一个选项,以便不选择任何内容的用户将不是一个选项。
如何实现验证,以便当用户尝试取消选择TableView中的最后一个选定选项时,它仍会保持选中状态?
确保将类设置为 UITableView 的委托,然后将其放入:
func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {
if let selectedIndices = tableView.indexPathsForSelectedRows {
return selectedIndices.count > 1 ? indexPath : nil
} else {
return nil
}
}
这样做是为了防止在没有选定单元格(实际上不应该发生(或只有 1 个选定单元格的情况下取消选择单元格。
它可能可以浓缩为这样:
func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {
return tableView.indexPathsForSelectedRows!.count > 1 ? indexPath : nil
}
因为我看不出如果您没有选择指示,您如何取消选择,但我不喜欢强制解开包装以防万一。