Is there any way to sort rows of a table view using a date/time? swift

Viewed 440

I have a messaging function in an app and I'm trying to sort the cells of a tableView based off a timestamp included with every message. I have two strings that are used to populate two different custom cells. Due to this, I can't just rearrange the contents of the string, I need to rearrange the rows themselves.

class messageThreadViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

func numberOfSections(in tableView: UITableView) -> Int {
    return 2
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
       return finalItems.count
    } else {
       return finalItems2.count
    }
}

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

    if indexPath.section == 0 {
      let cell = tableView.dequeueReusableCell(withIdentifier: "message1") as! MyTableViewCellThread
      cell.messagelabel?.text = finalItems[indexPath.row]
               return cell
    } else {
       let cell2 = tableView.dequeueReusableCell(withIdentifier: "message2") as! MyTableViewCellThread2
       cell2.messageLabel2?.text = finalItems2[indexPath.row]
               return cell2
    }
}

the two different strings are finalItems and finalitems2. I have attached an image of the app running to help get a better idea of what I'm trying to do. Let me know if I can explain it better. Thanks in advance!

screenshot simulator

1 Answers

In general, when sorting cells in tableviews, you simply sort the arrays (datasource) themselves and then call the tableView.reloadData() method. To sort arrays, the best practice is

let sortedArray = array.filter { $0.timestamp > $1.timestamp } 
// This sort with descending order, just replace '>' with '<'
Related