首页 > 解决方案 > 从 UITableView 获取所有单元格

问题描述

我想从 a中获取所有UITableView单元格,我知道tableView.visableCells将返回屏幕上可见的单元格数组,但我需要获取所有单元格。

下面大致是我计划如何实现这一点,但是我无法锻炼如何获得所有细胞,而不仅仅是可见细胞。用户将能够重新排序UITableView单元格,并且我希望能够在他们移动后记录每个单元格的索引,UITableViewCell这就是我需要所有单元格的原因

var textArray : [String] = [] // This is populated elsewhere and contains 30+ items
var textDict = [String:String]()


// allCellIndexPaths is a placeholder. I need to know how to get all Cell IndexPaths
for cellIndex in allCellIndexPaths { 
    let cell = tableView.cellForRow(at: cellIndex)
    let text = cell.textLabel.text
    textDict["Cell \(cellIndex.row)"] = text
}

想要这个的原因是我正在保存textDict到一个文件中,这样当用户重新排序单元格时,我正在保存他们的新索引,然后我可以按照我保存的索引值的顺序加载内容,即使应用程序已经完全完成关闭并重新打开。这也是为什么我不能只记录的值,sourceIndexPath因为destinationIndexPath这可能导致我的 dict 中的 2 个索引相同,这就是为什么我想获取每个单元格索引及其文本的列表。

绝对愿意以更好的方式做到这一点

标签: iosswiftuitableview

解决方案


我认为您不需要所有单元来实现重新排序单元。您只需要正确映射重新排序的索引路径。下面是链接,它有正确的例子来重新排序单元格。 https://www.ralfebert.de/ios-examples/uikit/uitableviewcontroller/reorderable-cells/

你需要在编辑模式下制作表格

self.tableView.isEditing = true

如果要在编辑模式下隐藏删除按钮,请使用:

override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    return .none
}

override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
    return false
}

通过覆盖 tableView:moveRowAtIndexPath: 启用重新排序控件移动单元格并实现该方法以便更新底层数据列表中的元素:

override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let movedObject = self.headlines[sourceIndexPath.row]
    headlines.remove(at: sourceIndexPath.row)
    headlines.insert(movedObject, at: destinationIndexPath.row)
}

推荐阅读