首页 > 解决方案 > 用字典分割表视图

问题描述

我有一本字典,其中存储了用户上传的数组膳食和日期。现在我想显示所有按日期存储和划分的膳食的表格视图。

如何设置所需的 numberOfSections()、titleForHeader()、numberOfRowsInSection() 和 cellForRowAt() 方法?

以下是我目前拥有但不起作用的内容

 var grouped = Dictionary<Date, [Meal]>()

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

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return Array(grouped)[section].key as! String
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var count = Array(grouped.keys)
    print(count)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows

    return Array(grouped.values)[section].count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "foodCell", for: indexPath)
    let meal = Array(grouped.values)[indexPath.row]
    cell.textLabel?.text = meal.foodname    //error here
    cell.detailTextLabel?.text = String(meal.calories) + "kJ"
    cell.detailTextLabel?.textColor = UIColor.secondaryLabel
    cell.accessoryType = .disclosureIndicator
    return cell
}

和我的 Meal 对象

class Meal: NSObject, Codable {

var id: String?
var foodname: String?
var date: Date?
}

标签: iosswiftuitableviewtableviewswift-dictionary

解决方案


推荐阅读