在 Swift 中对 table 视图进行排序后维护选定的单元格

Maintain selected cells after sorting a table view in Swift

我有一个 table 视图启用了多个 selection。用户应该能够 select 列表中的多个选项,然后更改列表的排序顺序。我希望能够保留相同的单元格 selected,但它们的顺序将与排序不同。我没有找到实现此目标的方法,因此欢迎提出任何建议。

如果您的数据结构中有 "selected" 指示器,您可以使用它来重建 tableView 选择。

如果您不能将此类指标添加到数据中,您可以分两步执行排序:1) 计算新元素索引,2) 将这些索引应用于数据数组以执行排序。

使用排序索引,您可以根据原始索引的新位置重建选择:

例如:

// Assuming your tableview is named "tableView",
// and the data array is named "dataArray",
// and you sort uses a member of dataArray called "sortKey"


// prepare list of new indexes for sorted data
let newIndexes   = dataArray.enumerated().sorted{ [=10=].1.sortKey < .1.sortKey }.map{[=10=].0}

// determine new indexes of current selection
let newSelection = tableView.indexPathsForSelectedRows?
                   .map{IndexPath(row:newIndexes.index(of:[=10=].row)!, section:0)}

// sort and reload the data                            
dataArray        = newIndexes.map{ self.dataArray[[=10=]] }
tableView.reloadData()

// reapply the selection
tableView.indexPathsForSelectedRows?.forEach{tableView.deselectRow(at:[=10=], animated:false)}
for indexPath in newSelection ?? []
{ self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) }