Swift - 如何通过其属性重新排序tableview中的所有单元格?

问题描述 投票:0回答:1

我有一个带细胞的tableView。还有items的类型是Dialog。这是cellForRow At函数:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


    let cell = tableView.dequeueReusableCell(withIdentifier: "DialogCell", for: indexPath) as! DialogCell

    var item: Dialog

    item = items[indexPath.row]

    ......

    return cell
}

现在,我想要做的是用item.getLastMessageCreateAt()的数量来命令这些单元格,它返回一个Int数字。我该怎么办?

到目前为止,这是我已经尝试过的:

func getAllCells() -> [UITableViewCell] {

    var cells = [UITableViewCell]()
    for i in 0...tableView.numberOfSections-1
    {
        for j in 0...tableView.numberOfRows(inSection: i)-1
        {
            if let cell = tableView.cellForRow(at: NSIndexPath(row: j, section: i) as IndexPath) {

                cells.append(cell)
            }

        }
    }
    return cells
}

func reorderCells() {

    var lastMessageAgoArray = [Int]()
    for item in self.items {
        lastMessageAgoArray.append(item.getLastMessageCreateAt())
    }
    let timeAgoInNumArrayBigToSmall: [Int] = lastMessageAgoArray.sorted { $0 > $1 }

    let cells = self.getAllCells()

    for cell in cells {
        let row = self.tableView.indexPath(for: cell)?.row
        if ( lastMessageAgoArray[row!] != timeAgoInNumArrayBigToSmall[row!] ) {
            if let index = timeAgoInNumArrayBigToSmall.index(of: lastMessageAgoArray[row!]) {
                self.tableView.moveRow(at: IndexPath(row: row!, section: 0), to: IndexPath(row: index, section: 0))
            }
            self.tableView.reloadData()
        }
    }

}

我试图运行这个,但我在这一行的末尾得到了nilrow

let row = self.tableView.indexPath(for: cell)?.row

那么我该如何订购这些细胞?

非常感谢你!

ios swift
1个回答
1
投票

将项目设置为:

items = myItemList.sorted { $0.getLastMessageCreateAt() > $1.getLastMessageCreateAt() } 

你可以保持func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)内的代码相同,并删除getAllCells()以及reorderCells()

您不希望对单元格进行排序,因为它们被tableview重用,具体取决于屏幕上当前可见的单元格。

© www.soinside.com 2019 - 2024. All rights reserved.