我有一个字典,其中包含一个日期的键值对,该日期包含一个由相同日期分组的我的自定义对象 "膳食 "数组。
饭菜对象。
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?
}
在我的TableView中
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中显示饭菜,按日期分类,并按最新日期排序。我如何实现这个目标?
为各部分创建一个结构
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
. 而且 从来没有 将属性声明为隐式拆包可选。
在你的数据模型中,你把你拥有的字典,每个条目有一天,把键作为一个数组,并对数组进行排序。
你的tableview有多少个节,就有多少个数组的条目。你从日期中创建每个部分的标题。对于每一个部分,你从字典中提取饭菜的数组,所以每一个部分都有不同的行数,每一行的数据都是从数组的一行中提取的。
例如,为了得到第3节第5行的数据,我们从索引3的日期数组中取出日期,在字典中查找日期并得到一个饭菜数组,索引5的饭菜提供了数据。