简体   繁体   中英

Swift - How to reorder all the cells in the tableview by its attribute?

I have a tableView with cells. There are also items whose type are Dialog . Here is the cellForRow At function:

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
}

Now, what I'd like to do is to order these cells with the number of item.getLastMessageCreateAt() , which returns an Int number. What should I do?

Up to now, here is what I have tried already:

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

}

I have tried to run this, but I got nil of the row at the end of this line:

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

So what should I do to order these cells?

Thank you very much!

Set items as:

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

And you can keep the code inside func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) the same, and remove getAllCells() as well as reorderCells() .

You don't want to sort the cells themselves as they are reused by the tableview depending on which cells are currently visible on the screen.

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