簡體   English   中英

重新排序tableview單元格

[英]Reordering tableview cells

我試圖根據其優先級(一個枚舉)對單元格重新排序。 我仔細檢查了我的枚舉值是否正確。 這是我的枚舉

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函數中,並且所有單元格都具有與其名稱相對應的優先級(“測試”除外),而且這些圖片是慢動作拍攝的,這意味着用戶將無法實際看到切換發生了。

中秋節SEGUE 電池開始切換

電池完成切換 電池完成切換

只需根據這些優先級對項目數組進行排序,然后重新加載表即可。

這樣,索引0只是第一項,以此類推,並且您將獲得簡單的代碼,這些代碼不會在即時進行排序/比較時造成混淆。

排序看起來像(在將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 })

您最好像這樣明確設置優先級值。

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

然后像這樣排序您的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