Ios Swift-如何按属性对tableview中的所有单元格重新排序

Ios Swift-如何按属性对tableview中的所有单元格重新排序,ios,swift,Ios,Swift,我有一个带单元格的桌面视图。还有一些项目的类型为对话框。以下是cellForRow At函数: func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DialogCell", for: indexPath) as! Dialo

我有一个带单元格的桌面视图。还有一些项目的类型为对话框。以下是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的编号对这些单元格进行排序,它返回一个整数。我该怎么办

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

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()
        }
    }

}
我曾尝试运行此命令,但在此行末尾我没有得到任何结果:

let row = self.tableView.indexPath(for: cell)?.row
那么我应该怎么做来订购这些细胞呢

多谢各位

将项目设置为:

items = myItemList.sorted { $0.getLastMessageCreateAt() > $1.getLastMessageCreateAt() } 
您可以将func tableView_utableview:UITableView、cellforrow和indexPath:indexPath中的代码保持不变,并删除getAllCells和reorderCells


您不希望对单元格本身进行排序,因为tableview会根据屏幕上当前可见的单元格重复使用这些单元格。

您的单元格只是数据的一个表达式。不要对单元格重新排序,先对数据重新排序,然后重新加载单元格。