我有一个启用了多个选择的表格视图。用户应该能够在列表中选择多个选项,然后更改列表的排序顺序。我希望能够保持选择相同的单元格,但它们的顺序将从排序中更改。我没有找到实现这一目标的方法,所以任何建议都值得赞赏。
答案 0 :(得分:0)
如果数据结构中有“选定”指示符,则可以使用它来重建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{ $0.1.sortKey < $1.1.sortKey }.map{$0.0}
// determine new indexes of current selection
let newSelection = tableView.indexPathsForSelectedRows?
.map{IndexPath(row:newIndexes.index(of:$0.row)!, section:0)}
// sort and reload the data
dataArray = newIndexes.map{ self.dataArray[$0] }
tableView.reloadData()
// reapply the selection
tableView.indexPathsForSelectedRows?.forEach{tableView.deselectRow(at:$0, animated:false)}
for indexPath in newSelection ?? []
{ self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) }