通过字典中的日期对表格视图进行剖分 [英] Sectioning a tableview by dates from a dictionary
问题描述
我有一个字典,其中包含Date的键/值对,Date包含按相同日期分组在一起的我的自定义对象Meals的数组.
I have a dictionary that contains a key/value pair of a Date that contains an array of my custom object Meals grouped together by the same dates.
膳食对象:
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中:
In my 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中显示餐点,按日期将其分段,并按最新的日期进行排序.我该如何实现?
This allows users to upload a meal multiple times a day for future viewing and now I want to show the meals in a TableView sectioned by their dates and sorted already by the latest. How do I achieve that?
推荐答案
为各节创建结构
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
实例更有意义.
You could add a date formatter to display the Date
instance more meaningful.
表视图数据源方法是
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
.并且从不将属性声明为隐式未包装的可选.
Consider to use less optionals and a struct rather than a NSObject
subclass. Unlike NSCoding
Codable
does not require to conform to NSObjectProtocol
. And never declare properties as implicit unwrapped optional.
这篇关于通过字典中的日期对表格视图进行剖分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!