[英]Get all Cells from UITableView
我想從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
的值,因為這可能導致我的字典中有 2 個相同的索引,這就是為什么我想獲取每個單元格索引及其文本的列表。
絕對開放更好的方法來做到這一點
我認為您不需要所有單元格來實現重新排序單元格。 您只需要 map 正確重新排序索引路徑。 下面是鏈接,其中包含重新排序單元格的正確示例。 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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.