0

我有一个字典,其中包含一个 Date 的键/值对,其中包含按相同日期分组在一起的自定义对象 Meals 的数组。

用餐对象:

class Meal: NSObject, Codable {

var id: String?
var foodname: String?
var quantity: Float!
var brandName: String?
var quantityType: String?
var calories: Float!
var date: Date?
}

在我的表视图中:

var grouped = Dictionary<Date, [Meal]>()
var listOfAllMeals = [Meal]() //already populated

self.grouped = Dictionary(grouping: self.listOfAllMeals.sorted(by: { ($0.date ?? nilDate) < ($1.date ?? nilDate) }),
            by: { calendar.startOfDay(for: $0.date ?? nilDate) })

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return grouped.count
}

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return Array(grouped.keys)[section] as! String //this throws a thread error
}

这允许用户每天多次上传餐点以供将来查看,现在我想在 TableView 中显示餐点,按日期划分并按最新排序。我该如何做到这一点?

4

2 回答 2

2

为这些部分创建一个结构

struct Section {
    let date : Date
    let meals : [Meal]
}

并将分组字典映射到一个数组Section

var sections = [Section]()

let sortedDates = self.grouped.keys.sorted(>)
sections = sortedDates.map{Section(date: $0, meals: self.grouped[$0]!)}

您可以添加日期格式化程序以显示Date更有意义的实例。

表视图数据源方法是

override func numberOfSections(in tableView: UITableView) -> Int {
    return sections.count
}

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {        
    return sections[section].date.description
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sections[section].meals.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "foodCell", for: indexPath)
    let meal = sections[indexPath.section].meals[indexPath.row]
    ...

笔记:

考虑使用更少的选项和结构而不是NSObject子类。不像NSCoding Codable不需要符合NSObjectProtocol. 并且永远不要将属性声明为隐式展开的可选。

于 2020-06-06T12:11:44.717 回答
0

在您的数据模型中,您使用每个条目一天的字典,将键作为数组,并对数组进行排序。

您的 tableview 具有与该数组具有条目一样多的部分。您从日期开始创建每个部分的标题。对于每个部分,您从字典中获取餐点数组,因此每个部分具有不同的行数,并且每个行中的数据取自数组的一行。

例如,要获取第 3 节第 5 行的数据,请从索引 3 处的日期数组中获取日期,在字典中查找日期并获取膳食数组,索引 5 处的膳食提供数据.

于 2020-06-06T12:09:11.587 回答