ios - 重新排序表格 View 单元格

标签 ios swift uitableview enums

我尝试根据优先级(枚举)对单元格重新排序。我仔细检查了我的枚举值是否正确。这是我的枚举

enum Priority{
    case low
    case neutral
    case high
    case urgent
}

如您所见,较低的优先级具有较低的哈希值。我正在尝试比较两个单元格;一个单元格及其上方的单元格。如果单元格的值大于它上面的值,它将向上移动。我使用

获取上面单元格的 IndexPath
var newIndexPath = IndexPath(row: indexPath.row - 1 , section: indexPath.section)

使用比较枚举值后

if(comparePriority.hashValue < priorityValue.hashValue)

我尝试使用

切换顺序
tableview.moveRow(at: indexPath, to: newIndexPath)

结果很有趣,我会用图片来解释。请注意,所有这些代码都在我的 cellForRowAt 函数中,并且所有单元格都被赋予与其名称相对应的优先级,除了“测试”之外,而且这些照片是以慢动作拍摄的,这意味着用户将无法真正看到发生的切换。

中段 Cells start switching

细胞完成切换 Cells finish switching

最佳答案

只需根据这些优先级对项目数组进行排序,然后重新加载表格即可。

这样,索引 0 就是第一个项目等等,您将获得简单的代码,不会因在整个地方进行即时排序/比较而感到困惑。

排序看起来像(在您将 enum 设为 Int 并将 priorityValue 重命名为 priority 我建议你这样做):

enum Priority: Int
{
    case low     = 0
    case neutral = 1
    case high    = 2
    case urgent  = 3
}

items.sorted(by: { $0.priority < $1.priority })

关于ios - 重新排序表格 View 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45361169/

相关文章:

objective-c - MFMessageComposeViewController 的替代品

ios - viewcontrller 中的应用程序委托(delegate)功能 - Facebook

swift - 从 Firebase 更改为 Firestore 导致查询中出现 fatal error : Unexpectedly found nil . ..

ios - 在 Swift 中的 ViewController 之间传递数组/对象

ios - iOS 中是否有等效的 Android sharedpreferences 来保存凭据(用户名和密码)?

ios - Xcode Storyboard 中的图像随机扭曲

swift - NSTimer Swift 难度

ios - 为什么它需要 tableView(_ :indentationLevelForRowAt:) when Inserting cell into a table view with static cells

ios - 将分页集成到自动完成本地搜索中

objective-c - Objective-C : How to reload tableview immediately after switching tabs?