简体   繁体   English

重新排序tableview单元格

[英]Reordering tableview cells

I a trying to re order cells based on their priority (an enum). 我试图根据其优先级(一个枚举)对单元格重新排序。 I have double checked that my enum values are correct. 我仔细检查了我的枚举值是否正确。 Here is my enum 这是我的枚举

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

As you can see, the lower priority has lower hash values. 如您所见,较低的优先级具有较低的哈希值。 I am trying to compare two cells; 我正在尝试比较两个单元格; a cell and the cell above it. 一个单元格及其上方的单元格。 If the cell's value is greater than the one above it, it will shift upwards. 如果该单元格的值大于其上方的值,它将向上移动。 I obtain the IndexPath of the cell above using 我使用以下方法获取上面单元格的IndexPath

var newIndexPath = IndexPath(row: indexPath.row - 1 , section: indexPath.section)

After comparing enum values using 比较枚举值后使用

if(comparePriority.hashValue < priorityValue.hashValue)

I attempt to switch the order using 我尝试使用切换订单

tableview.moveRow(at: indexPath, to: newIndexPath)

The result is interesting, I will use pictures to explain. 结果很有趣,我将使用图片进行解释。 Note that all of this code is in my cellForRowAt function and that all cells are given the priority that correspond with their name except for "test", also that these pictures were taken in slow motion meaning that the user wouldn't be able to actually see the switch happening. 请注意,所有这些代码都在我的cellForRowAt函数中,并且所有单元格都具有与其名称相对应的优先级(“测试”除外),而且这些图片是慢动作拍摄的,这意味着用户将无法实际看到切换发生了。

Mid-segue 中秋节SEGUE 电池开始切换

Cells finish switching 电池完成切换 电池完成切换

Just sort your array of items according to these priorities and then do a table reload. 只需根据这些优先级对项目数组进行排序,然后重新加载表即可。

In that way index 0 is simply the first item etc. and you'll get simple code that's not confusing by on the fly sorting/comparing all over the place. 这样,索引0只是第一项,以此类推,并且您将获得简单的代码,这些代码不会在即时进行排序/比较时造成混淆。

Sorting would look something like (after you've made your enum of type Int and renamed priorityValue to priority which I suggest you do): 排序看起来像(在将enum类型设置为Int并将重命名priorityValue priority重命名为priorityValue priority ,我建议您这样做):

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

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

You better set priority value explicitly like this. 您最好像这样明确设置优先级值。

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

and sort your dataSource array like 然后像这样排序您的dataSource数组

dataSource = dataSource.sorted(by: { $0.priority < $1.priority })
tableView.reloadDate()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM