简体   繁体   中英

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

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.

Mid-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.

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 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.sorted(by: { $0.priority < $1.priority })
tableView.reloadDate()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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