ios - 根据 TableView 部分和行重新排序(重新定位)数据模型

标签 ios swift uitableview

假设我有几个工作日的部分和我当天锻炼的几行。

所以结构可能是下一个

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 sourceIndexPathdestinationIndexPath

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/

相关文章:

ios - 点击时动态更改 uitableviewcell 高度

ios - 从 URL 加载 UIImage 时在 UITableViewCell 中设置 UIImageView 大小?

ios - Xcode 5.1 : missing required architecture arm64

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

ios - 为什么 IBOutlet var 在模拟器上运行时有值(value),但在设备上运行时产生 nil?

ios - 如何使用 XCode 6 在 iOS 7 的 UItableviewCell 中制作 UIlabel 的动态高度

objective-c - 在 iOS 应用程序中设置配置文件的最佳方法

ios - 网络连接应仅在更改时出现

ios - 如何从 Parse.com 获取单个键的所有值

iOS In App Purchase in Action Extension 应用程序