【发布时间】:2018-11-19 10:58:23
【问题描述】:
有人能说出用字典数组填充 tableView 的简洁高效的方法吗?我有模型Sale,其中包含 saleAmount、soldBy、division、saleDate。每个部门可能包含许多销售数据,并希望按每个部门分隔销售数据。此外,在 tableView 标题中,我想显示部门名称以及特定部门的总销售额
class Sale {
var saleAmount : Double = 0.00
var soldBy : String = ""
var division : String = ""
var saleDate : Date?
}
我收到数据并存储在
var sales : [Sale] = [Sale]()
然后我将数据处理到每个“部门”的字典中
var salesDict : [String : Sale] = [String : Sale] ()
func createIndex<Key, Element>(elms:[Element], extractKey:(Element) -> Key) -> [Key:Element] where Key : Hashable {
return elms.reduce([Key:Element]()) { (dict, elm) -> [Key:Element] in
var dict = dict
dict[extractKey(elm)] = elm
return dict
}
}
salesDict = createIndex(elms: sales, extractKey: {$0.division})
salesSection = salesDict.compactMap(){$0.key} // To store keys
print(saleDict) // ["division1": Clientname.Sale, "division2": Clientname.Sale, "division3": Clientname.Sale, "division4": Clientname.Sale]
并填充 tableView
func numberOfSections(in tableView: UITableView) -> Int {
return salesSection.count
}
数据未正确填充
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return [salesDict[salesSection[section]]?.soldBy].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let saleItem = salesDict[salesSection[indexPath.section]]
let cell = tableView.dequeueReusableCell(withIdentifier: "FoldingCell", for: indexPath) as! SaleHistoryTableViewCell
cell.saleAmountLabel.text = ("\(String(describing: saleItem?.saleAmount))")
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return salesSection[section]
}
【问题讨论】:
-
你能详细说明
Data is not populating correctly吗? -
我能够将对象数组转换为每个部门的字典。但是对于每个部门,只有一条记录填充在 tableview 中。看到 Fabio 的解决方案后,我觉得我在创建 var salesDict 时犯了一个错误:[String : Sale] = [String : Sale] ()。它应该是 var salesDict : [String : [Sale]] = [String : [Sale]] () 代替。
标签: ios arrays swift uitableview dictionary