Swift,带有tableview的弹出窗口在从未单击过的位置显示复选标记
我尝试显示一个弹出窗口,用户可以在其中选择多行来过滤数据。为此,我创建了此popupViewcontroller:Swift,带有tableview的弹出窗口在从未单击过的位置显示复选标记,swift,tableview,Swift,Tableview,我尝试显示一个弹出窗口,用户可以在其中选择多行来过滤数据。为此,我创建了此popupViewcontroller: func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCell.AccessoryType.checkmark{ t
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCell.AccessoryType.checkmark{
tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCell.AccessoryType.none
checkedCategories.remove(at: indexPath.row)
}else{
tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCell.AccessoryType.checkmark
checkedCategories.append(allcategories[indexPath.row])
}
}
但问题是,如果用户单击第一个位置,最后一项也会显示复选标记。只有在滚动后才会发生此错误。这是因为单元格已出列,所以在
cellForRowAt内
cell.accessoryType = checkedCategories.contains(indexPath.row) ? .checkmark : .none
另一个可能导致崩溃的注意事项是取消使用
checkedCategories.removeAll(where:{ $0 == indexPath.row })
不要使用单独的数组来保留索引路径。这是非常糟糕的做法 细胞被重复使用。您必须确保每个UI元素都设置为
cellForRow
中定义的状态
在数据模型中,最好是结构或类添加属性
var isSelected = false
在cellForRow
中,根据属性设置复选标记
let item = datasource[indexPath.row]
cell.accessoryType = item.isSelected ? .checkmark : .none
在didSelectRowAt
中,切换isSelected
并重新加载行
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
datasource[indexPath.row].isSelected.toggle()
tableView.reloadRows(at: [indexPath], with: .none)
}