假设我有几个工作日的部分和我当天锻炼的几行。
所以结构可能是下一个
Monday section 0
Workout 1 (row 0)
Workout 2 (row 1)
Tuesday section 1
Workout 1 (row 0)
Workout 2 (row 1)
因此,当我在部分之间移动单元格时,我想重新定位我的元素,实际上是在部分中锻炼。
目前我有数据模型
class Workout {
var position: Int
}
现在,当我将一个单元格从一个部分移动到另一个部分时,我需要循环遍历我的 [workouts]
数组以重新计算源部分和目标部分中的位置。
也许有一些漂亮的解决方案,例如带有第一个和最后一个元素的 List
,我可以简单地重新绑定(bind)它们或任何其他元素。
我看到没有列表 here
最佳答案
要处理 tableView
中的重新排序,您可以简单地使用它的 UITableViewDataSource
方法。
示例:
我们将使用下面的数组
作为tableView的
dataSource
:
var arr = [["First", "Second"], ["Third", "Fourth"]]
要在单元格重新排序时修改 dataSource
,请使用 tableView(_:moveRowAt:to:)
方法并根据以下内容更改 dataSource
sourceIndexPath
和 destinationIndexPath
。
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let val = arr[sourceIndexPath.section][sourceIndexPath.row]
arr[destinationIndexPath.section][destinationIndexPath.row] = val
arr[sourceIndexPath.section].remove(at: sourceIndexPath.row)
}
此外,如前所述,Swift
中没有类似List
的东西。您必须使用 Array
来处理它。
关于ios - 根据 TableView 部分和行重新排序(重新定位)数据模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56219975/