Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift,带有tableview的弹出窗口在从未单击过的位置显示复选标记_Swift_Tableview - Fatal编程技术网

Swift,带有tableview的弹出窗口在从未单击过的位置显示复选标记

Swift,带有tableview的弹出窗口在从未单击过的位置显示复选标记,swift,tableview,Swift,Tableview,我尝试显示一个弹出窗口,用户可以在其中选择多行来过滤数据。为此,我创建了此popupViewcontroller: func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCell.AccessoryType.checkmark{ t

我尝试显示一个弹出窗口,用户可以在其中选择多行来过滤数据。为此,我创建了此popupViewcontroller:

 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)
}