如何在表格视图中按日期对项目进行排序 Swift 3

How to sort items by date in tableview Swift 3

所以在我的应用程序中,用户可以创建费用并按月存储和查看它们。目前,我所有的费用都按照我添加的顺序显示,但我希望它们按日期顺序显示,我还希望有一个带有日期的 tableviewheader,以便将费用组合在一起。我在 viewdidLoad 中尝试了这段代码。

for expense in monthlyExpenses{
        if let dateString = expense.modificationDate?.convertToString(){
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = DateFormatter.Style.medium
        dateFormatter.timeStyle = DateFormatter.Style.none
        let finalDate = dateFormatter.date(from: dateString)
        if let finalDate = finalDate{
            let dateString2 = finalDate.timeIntervalSinceReferenceDate
            if self.toDoList[dateString2] == nil {
                self.toDoList[dateString2] = [expense.name!]
            }
            else {
                self.toDoList[dateString2]?.append(expense.name!)
            }
        }
    }
    }

然后在我的 tableviewheader 部分尝试了这段代码,但是得到了 EXC_BAD_INSTRUCTION 错误。

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    let dateDouble = self.sortedSections[section]

    let date = Date(timeIntervalSinceReferenceDate: dateDouble)

    let dateformatter = DateFormatter()

    dateformatter.dateStyle = DateFormatter.Style.medium

    dateformatter.timeStyle = DateFormatter.Style.none

    return dateformatter.string(from: date)

}

每笔费用都是一个单独的对象,存储在核心数据中,具有名称、金额、修改日期等属性。我希望它们按修改日期排序。我将如何去做这件事?

我做过类似的事情,但我正在使用一个已经有 xib 和方法来调整一切的库。这只是我这边的一个小帮助。

你可以准备一个xib来在tableView中显示日期和数据。在这里,如果下一个日期与上一个日期相同,您可以隐藏该行,并在日期更改时显示。 要根据日期显示数据,您可以这样做(如果根据日期添加数据

let expenses = [ExpensesClass]()

// in `cellForItemAt indexPath`

let expense = expenses[indexPath.row]
    let date = expense.date
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MMMM d, yyyy"
    let dateString = dateFormatter.string(from: date! as Date)

. . . . . . 

if indexPath.row > 0 {
        let previousExpensesData = expenses[indexPath.row - 1].date  
        let day = Calendar.current.component(.day, from: expense.date) // Do not add above 'date' value here, you might get some garbage value. I know the code is redundant. You can adjust that.
        let previousDay = Calendar.current.component(.day, from: expenses[indexPath.row - 1].date)
            if day == previousDay {
                cell.dateTitle.text = ""
            } else {
                  cell.dateTitle.text = dateString
            }
    }else{
        cell.dateTitle.text = dateString
        print("Cannot return previous Message Index...\n\n")
    }

您可以通过此方法调整高度 -> func tableView(UITableView, heightForRowAt: IndexPath).

我不确定这个方法 -> func tableView(UITableView, titleForHeaderInSection: Int)。如果上述方法不适合您,您也可以尝试使用此方法,并在 -> func tableView(UITableView, titleForHeaderInSection: Int)

中相应地调整高度
func tableView(_ tableView: UITableView, 
     heightForRowAt indexPath: IndexPath) -> CGFloat
{
    let expense = expenses[indexPath.row]

    if indexPath.row > 0{
        let day = Calendar.current.component(.day, from: expense.date)
        let previousDay = Calendar.current.component(.day, from: expense[indexPath.row - 1].date) 
        if day == previousDay {
            return 0.0
        }else{
             return 20.0
        }
    }
    return 20.0
}

1.创建一个字典,其中包含日期作为键和修改或放置在其上的订单数组作为值。

var orderDictionary[日期:[订单]?] = [:]

for order in yourOrders {
  
  var orders = orderDictionary[order.modificationDate] ?? []
  
  if orders.count == 0 {
     orderDictionary[order.modificationDate] = [order]
  } else {
     orders.append(order)
     orderDictionary[order.modificationDate] = orders
  }
}

2。从字典中排序键数组。

let dateArray = orderDictionary.keys

dateArray.sort { [=12=] < }

根据您的要求更改比较条件,例如是升序还是降序。

3。在func tableView(UITableView, titleForHeaderInSection: Int)中写入

return dateArray[section] 或根据需要格式化日期。

4。在numberOfRowsForSection中写入

return orderDictionary[dateArray[section]].count

5.在cellForRowAtIndexPath中写入

let order = orderDictionary[dateArray[indexPath.section]][indexPath.row]