ios - 从 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 个索引相同,这就是为什么我想获取每个单元格索引及其文本的列表。
绝对愿意以更好的方式做到这一点
解决方案
我认为您不需要所有单元来实现重新排序单元。您只需要正确映射重新排序的索引路径。下面是链接,它有正确的例子来重新排序单元格。 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)
}
推荐阅读
- ruby - 循环遍历字符串会在 Ruby 中的字符之间添加空格
- visual-studio-code - VS 代码,运行 gulp 任务。不接受价值。有效值:“外壳”
- vb.net - 如何从数据库中删除数据
- c# - 自适应卡片未在 WebChat 中呈现
- html - 如何通过 ng-content 传递数据?
- android - 带有工具栏的 AppBarLayout 没有阴影/高度
- angular - 表单无效时测试按钮被禁用
- r - R:使用条件将垂直数据转换为水平格式
- asp.net - EntityFramework Core 加入后得到多个结果
- c# - 在 C# 中保存来自 Word 邮件合并的新文档结果